-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathSearchAWordIn2dGrid.py
82 lines (70 loc) · 2.34 KB
/
SearchAWordIn2dGrid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
/**
@author Anirudh Sharma
Given a 2D grid of characters and a word, find all occurrences of given word in grid.
A word can be matched in all 8 directions at any point.
Word is said be found in a direction if all characters match in this direction
(not in zig-zag form). The 8 directions are, horizontally left, horizontally right,
vertically up, vertically down and 4 diagonal directions.
Constraints:
1 <= n <= m <= 100
1 <= |word| <= 10
"""
# Coordinates for searching in all eight directions
x = [-1, -1, -1, 0, 0, 1, 1, 1]
y = [-1, 0, 1, -1, 1, -1, 0, 1]
def doesWordExist(grid, row, column, word):
# Check if the current character in the
# grid matches with the first character
# in the word
if grid[row][column] != word[0]:
return False
# Check word in all eight directions
for i in range(8):
# Starting position for the current direction
rowDirection = row + x[i]
columnDirection = column + y[i]
# number of matched characters
matchedCount = 1
# Since first character is already checked,
# we check for remaining characters
for j in range(1, len(word)):
# Check for out of bounds
if rowDirection < 0 or rowDirection >= len(grid) or columnDirection < 0 or columnDirection >= len(grid[0]):
break
# If the characters don't match
if grid[rowDirection][columnDirection] != word[j]:
break
# Updated matched count
matchedCount += 1
# Move in a particular direction
rowDirection += x[i]
columnDirection += y[i]
# Check if all the characters match
if matchedCount == len(word):
return True
return False
def search(grid, word):
# List to store the result
result = []
# Loop through every cell of the grid
for i in range(len(grid)):
for j in range(len(grid[0])):
if doesWordExist(grid, i, j, word):
result.append([i, j])
return result
if __name__ == "__main__":
grid = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
]
word = "abc"
print(search(grid, word))
grid = [
['a', 'b', 'a', 'b'],
['a', 'b', 'e', 'b'],
['e', 'b', 'e', 'b']
]
word = "abe"
print(search(grid, word))