-
Notifications
You must be signed in to change notification settings - Fork 43
/
word-search.py
340 lines (283 loc) · 11.4 KB
/
word-search.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
"""
79. Word Search
Medium
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board and word consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
"""
# V0
# IDEA : DFS + backtracking
class Solution(object):
def exist(self, board, word):
### NOTE : construct the visited matrix
visited = [[False for j in range(len(board[0]))] for i in range(len(board))]
"""
NOTE !!!! : we visit every element in board and trigger the dfs
"""
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, word, 0, i, j, visited):
return True
return False
def dfs(self, board, word, cur, i, j, visited):
# if "not false" till cur == len(word), means we already found the wprd in board
if cur == len(word):
return True
### NOTE this condition
# 1) if idx out of range
# 2) if already visited
# 3) if board[i][j] != word[cur] -> not possible to be as same as word
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j] or board[i][j] != word[cur]:
return False
# NOTE THIS !! : mark as visited
visited[i][j] = True
### NOTE THIS TRICK (run the existRecu on 4 directions on the same time)
result = self.dfs(board, word, cur + 1, i + 1, j, visited) or\
self.dfs(board, word, cur + 1, i - 1, j, visited) or\
self.dfs(board, word, cur + 1, i, j + 1, visited) or\
self.dfs(board, word, cur + 1, i, j - 1, visited)
# mark as non-visited
visited[i][j] = False
return result
# V0'
# IDEA : DFS
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for y in range(len(board)):
for x in range(len(board[0])):
if self.dfs(board, word, x, y, 0):
return True
return False
def dfs(self, board, word, x, y, i):
if i == len(word):
return True
if x < 0 or x >= len(board[0]) or y < 0 or y >= len(board):
return False
if board[y][x] != word[i]:
return False
board[y][x] = board[y][x].swapcase() # to mark if the route already been passed (.swapcase(), e.g. A->a)
isExit = self.dfs(board, word, x + 1, y, i + 1) or self.dfs(board, word, x, y + 1, i + 1) or self.dfs(board, word, x - 1, y, i + 1) or self.dfs(board, word, x, y - 1, i + 1)
board[y][x] = board[y][x].swapcase() # if already visited all possible route within the route collection, then roll back the maked route (.swapcase(), e.g. a->A), and run the other visit again
return isExit
# V1
# IDEA : BACKTEACKING
# https://leetcode.com/problems/word-search/solution/
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
self.ROWS = len(board)
self.COLS = len(board[0])
self.board = board
for row in range(self.ROWS):
for col in range(self.COLS):
if self.backtrack(row, col, word):
return True
# no match found after all exploration
return False
def backtrack(self, row, col, suffix):
# bottom case: we find match for each letter in the word
if len(suffix) == 0:
return True
# Check the current status, before jumping into backtracking
if row < 0 or row == self.ROWS or col < 0 or col == self.COLS \
or self.board[row][col] != suffix[0]:
return False
ret = False
# mark the choice before exploring further.
self.board[row][col] = '#'
# explore the 4 neighbor directions
for rowOffset, colOffset in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
ret = self.backtrack(row + rowOffset, col + colOffset, suffix[1:])
# break instead of return directly to do some cleanup afterwards
if ret: break
# revert the change, a clean slate and no side-effect
self.board[row][col] = suffix[0]
# Tried all directions, and did not find any match
return ret
# V1
# IDEA : BACKTEACKING
# https://leetcode.com/problems/word-search/solution/
def backtrack(self, row, col, suffix):
"""
backtracking with side-effect,
the matched letter in the board would be marked with "#".
"""
# bottom case: we find match for each letter in the word
if len(suffix) == 0:
return True
# Check the current status, before jumping into backtracking
if row < 0 or row == self.ROWS or col < 0 or col == self.COLS \
or self.board[row][col] != suffix[0]:
return False
# mark the choice before exploring further.
self.board[row][col] = '#'
# explore the 4 neighbor directions
for rowOffset, colOffset in [(0, 1), (-1, 0), (0, -1), (1, 0)]:
# sudden-death return, no cleanup.
if self.backtrack(row + rowOffset, col + colOffset, suffix[1:]):
return True
# revert the marking
self.board[row][col] = suffix[0]
# Tried all directions, and did not find any match
return False
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79386066
# IDEA : BACKTRACKING
# DEMO :
# In [39]: 'ACV'.swapcase()
# Out[39]: 'acv'
# In [41]: 'wfwwrgergewCEVER'.swapcase()
# Out[41]: 'WFWWRGERGEWcever'
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
for y in range(len(board)):
for x in range(len(board[0])):
if self.exit(board, word, x, y, 0):
return True
return False
def exit(self, board, word, x, y, i):
if i == len(word):
return True
if x < 0 or x >= len(board[0]) or y < 0 or y >= len(board):
return False
if board[y][x] != word[i]:
return False
board[y][x] = board[y][x].swapcase() # to mark if the route already been passed (.swapcase(), e.g. A->a)
isexit = self.exit(board, word, x + 1, y, i + 1) or self.exit(board, word, x, y + 1, i + 1) or self.exit(board, word, x - 1, y, i + 1) or self.exit(board, word, x, y - 1, i + 1)
board[y][x] = board[y][x].swapcase() # if already visited all possible route within the route collection, then roll back the maked route (.swapcase(), e.g. a->A), and run the other visit again
return isexit
# V1'
# https://www.cnblogs.com/zuoyuan/p/3769767.html
# IDEA : DFS
class Solution:
# @param board, a list of lists of 1 length string
# @param word, a string
# @return a boolean
def exist(self, board, word):
def dfs(x, y, word):
if len(word)==0: return True
#left
if x>0 and board[x-1][y]==word[0]:
tmp=board[x][y]; board[x][y]='#'
if dfs(x-1,y,word[1:]):
return True
board[x][y]=tmp
#right
if x<len(board)-1 and board[x+1][y]==word[0]:
tmp=board[x][y]; board[x][y]='#'
if dfs(x+1,y,word[1:]):
return True
board[x][y]=tmp
#down
if y>0 and board[x][y-1]==word[0]:
tmp=board[x][y]; board[x][y]='#'
if dfs(x,y-1,word[1:]):
return True
board[x][y]=tmp
#up
if y<len(board[0])-1 and board[x][y+1]==word[0]:
tmp=board[x][y]; board[x][y]='#'
if dfs(x,y+1,word[1:]):
return True
board[x][y]=tmp
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==word[0]:
if(dfs(i,j,word[1:])):
return True
return False
# V1''
# https://www.jiuzhang.com/solution/word-search/#tag-highlight-lang-python
class Solution:
# @param board, a list of lists of 1 length string
# @param word, a string
# @return a boolean
def exist(self, board, word):
# write your code here
# Boundary Condition
if word == []:
return True
m = len(board)
if m == 0:
return False
n = len(board[0])
if n == 0:
return False
# Visited Matrix
visited = [[False for j in range(n)] for i in range(m)]
# DFS
for i in range(m):
for j in range(n):
if self.exist2(board, word, visited, i, j):
return True
return False
def exist2(self, board, word, visited, row, col):
if word == '':
return True
m, n = len(board), len(board[0])
if row < 0 or row >= m or col < 0 or col >= n:
return False
if board[row][col] == word[0] and not visited[row][col]:
visited[row][col] = True
# row - 1, col
if self.exist2(board, word[1:], visited, row - 1, col) or self.exist2(board, word[1:], visited, row, col - 1) or self.exist2(board, word[1:], visited, row + 1, col) or self.exist2(board, word[1:], visited, row, col + 1):
return True
else:
visited[row][col] = False
return False
# V2
# Time: O(m * n * l)
# Space: O(l)
class Solution(object):
# @param board, a list of lists of 1 length string
# @param word, a string
# @return a boolean
def exist(self, board, word):
visited = [[False for j in range(len(board[0]))] for i in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if self.existRecu(board, word, 0, i, j, visited):
return True
return False
def existRecu(self, board, word, cur, i, j, visited):
if cur == len(word):
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j] or board[i][j] != word[cur]:
return False
visited[i][j] = True
result = self.existRecu(board, word, cur + 1, i + 1, j, visited) or\
self.existRecu(board, word, cur + 1, i - 1, j, visited) or\
self.existRecu(board, word, cur + 1, i, j + 1, visited) or\
self.existRecu(board, word, cur + 1, i, j - 1, visited)
visited[i][j] = False
return result