79 单词搜索
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
解法
- 回溯
class Solution:
orientation = [(0, -1), (-1, 0), (1, 0), (0, 1)]
def exist(self, board, word):
m = len(board)
if m == 0: return False
n = len(board[0])
mark = [[False for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
if self.DFS(board, word, 0, i, j, mark, m, n):
return True
return False
def DFS(self, board, word, index, start1, start2, mark, m, n):
if index == len(word)-1:
return word[index] == board[start1][start2]
if board[start1][start2] == word[index]:
mark[start1][start2] = True
for k in self.orientation:
start_x = start1+k[0]
start_y = start2+k[1]
if 0 <= start_x < m and 0 <= start_y < n:
if not mark[start_x][start_y] and self.DFS(
board, word, index+1, start_x, start_y, mark, m, n):
return True
mark[start1][start2] = False
return False