https://www.hackerrank.com/challenges/the-grid-search/forum

http://blog.sina.com.cn/s/blog_6a09b5a70100nhnr.html

 1 # 2D Rabin-Karp Algorithm
2 import re
3
4 MOD = 10 ** 9 + 7
5
6 def get2DMatrix(n, m):
7     a = [[0 for j in xrange(m)] for i in xrange(n)]
8     return a
9
10 def calcHash(a, nn, mm):
11     n = len(a)
12     m = len(a[0])
13
14     b = 1
15     for i in xrange(mm):
16         b = b * 10 % MOD
17     b2 = 1
18     for i in xrange(nn):
19         b2 = b2 * b % MOD
20
21     h = get2DMatrix(n, m)
22     for i in xrange(n):
23         val = 0
24         for j in xrange(m):
25             val = (val * 10 + a[i][j]) % MOD
26             if j >= mm:
27                 val = (val + a[i][j - mm] * (MOD - b)) % MOD
28             h[i][j] = val
29
30     h2 = get2DMatrix(n, m)
31     h2[0] = h[0][:]
32     for i in xrange(1, n):
33         for j in xrange(m):
34             h2[i][j] = (h2[i - 1][j] * b + h[i][j]) % MOD
35             if i >= nn:
36                 h2[i][j] = (h2[i][j] + h[i - nn][j] * (MOD - b2)) % MOD
37     return h, h2
38
39 def equal(a, p, ai, aj):
40     np = len(p)
41     mp = len(p[0])
42     for i in xrange(np):
43         for j in xrange(mp):
44             if a[ai + i][aj + j] != p[i][j]:
45                 return False
46     return True
47
48 def solve():
49     na, ma = map(int, re.split('\s+', raw_input().strip()))
50     a = []
51     for i in xrange(na):
52         a.append(map(int, list(raw_input().strip())))
53     np, mp = map(int, re.split('\s+', raw_input().strip()))
54     p = []
55     for i in xrange(np):
56         p.append(map(int, list(raw_input().strip())))
57     ha, h2a = calcHash(a, np, mp)
58     hp, h2p = calcHash(p, np, mp)
59
60     for i in xrange(np - 1, na):
61         for j in xrange(mp - 1, ma):
62             if h2a[i][j] != h2p[np - 1][mp - 1]:
63                 continue
64             if equal(a, p, i - np + 1, j - mp + 1):
65                 print('YES')
66                 return
67     print('NO')
68
69 if __name__ == '__main__':
70     t = int(raw_input())
71     for ti in xrange(t):
72         solve()
73         

posted on 2015-07-30 01:48  zhuli19901106  阅读(962)  评论(1编辑  收藏  举报