题目
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
提示:
board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
解题思路
dfs, change the value in matrix for keeping track of visited nodes
Time complexity:
o
(
m
∗
n
)
o(m * n)
o(m∗n),
m
,
n
m, n
m,n分别是board
的宽度和高度
Space complexity:
o
(
m
∗
n
+
l
e
n
(
w
o
r
d
)
)
o(m * n + len(word))
o(m∗n+len(word))
代码
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m, n = len(board), len(board[0])
visited = set()
def dfs(x: int, y: int, index: int) -> bool:
if index == len(word) - 1:
return True
res = False
for dz in (-1, 1):
if 0 <= x + dz < m and board[x + dz][y] == word[index + 1] and (x + dz, y) not in visited:
visited.add((x + dz, y))
res |= dfs(x + dz, y, index + 1)
visited.remove((x + dz, y))
if 0 <= y + dz < n and board[x][y + dz] == word[index + 1] and (x, y + dz) not in visited:
visited.add((x, y + dz))
res |= dfs(x, y + dz, index + 1)
visited.remove((x, y + dz))
return res
res = False
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
visited.add((i, j))
res |= dfs(i, j, 0)
visited.remove((i, j))
if res:
return True
return False