1+ """
2+ Refer below link for the question:
3+ https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/
4+
5+ Solution:
6+ Algorithm for this is already present, but expected solution should
7+ have lowest time complexity (the algorithm should only traverse once unlike the
8+ solution above which traverses whole matrix for each word given)
9+
10+ Enhancement:
11+ if the word is not present in the grid, print word along with row
12+ and col as (-1,-1) like word,-1,-1
13+
14+ Hint:
15+ Use DP approach
16+
17+ Solution that I have gone with is below:
18+
19+ """
20+
21+ # Enter your code here. Read input from STDIN. Print output to STDOUT
22+ import sys
23+ class word_seek :
24+
25+ def __init__ (self ):
26+ self .R = None
27+ self .C = None
28+ self .dir = [[- 1 , 0 ], [1 , 0 ], [1 , 1 ],
29+ [1 , - 1 ], [- 1 , - 1 ], [- 1 , 1 ],
30+ [0 , 1 ], [0 , - 1 ]]
31+ def search_grid (self , grid , row , col , word ):
32+ if grid [row ][col ] != word [0 ]:
33+ return False
34+ for x , y in self .dir :
35+ rd , cd = row + x , col + y
36+ flag = True
37+ for k in range (1 , len (word )):
38+ if (0 <= rd < self .R and
39+ 0 <= cd < self .C and
40+ word [k ] == grid [rd ][cd ]):
41+ rd += x
42+ cd += y
43+ else :
44+ flag = False
45+ break
46+ if flag :
47+ return True
48+ return False
49+ def patternSearch (self , grid , word ):
50+ self .R = len (grid )
51+ self .C = len (grid [0 ])
52+ tracker = []
53+ for row in range (self .R ):
54+ for col in range (self .C ):
55+ if self .search_grid (grid , row , col , word ):
56+ tracker .append ((word ,row ,col ))
57+ else :
58+ tracker .append ((word ,- 1 ,- 1 ))
59+ if len (set (tracker )) > 1 :
60+ tracker = sorted (tracker ,key = lambda x : x [1 ],reverse = True )
61+ print (tracker [0 ][0 ],tracker [0 ][1 ],tracker [0 ][2 ])
62+ return
63+ else :
64+ assert (tracker [0 ][1 ] == - 1 ) and (tracker [0 ][2 ] == - 1 ),"failed"
65+ print (tracker [0 ][0 ],tracker [0 ][1 ],tracker [0 ][2 ])
66+ return
67+
68+ if __name__ == '__main__' :
69+ grid = sys .stdin .readlines ()
70+ grid = [i .strip () for i in grid ]
71+ ind = grid .index ('' )
72+ #grid = grid[:(ind)]
73+ #finders = grid[(ind+1):]
74+ #print (grid)
75+ #print (finders)
76+ wordSeek = word_seek ()
77+ for w in grid [(ind + 1 ):]:
78+ wordSeek .patternSearch (grid [:(ind )],w )
0 commit comments