给定一个二维网格和一个单词,找出该单词是否存在于网格中。
Words must be in alphabetical order and formed by letters in adjacent cells, where "adjacent" cells are those that are adjacent horizontally or vertically. Letters in the same cell are not allowed to be reused.
Example:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = " ABCCED ", return true Given word =" SEE ", return true Given word = " ABCB ", return false
prompt:
board
Andword
it contains only uppercase and lowercase letters.1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
DFS+backtracking
When you see a two-dimensional table, you think of DFS. It traverses the entire two-dimensional table. DFS is executed when the current position is the beginning letter of word. At the same time, a vis array is added to indicate the visited position, and then some judgment conditions are added.
Code
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(x, y, tmp):
nonlocal flag
if tmp == word:
flag = True
return
if not (0 <= x < rowLength and 0 <= y < colLength):
return
if flag or vis[x][y] or board[x][y] != word[len(tmp)]:
return
vis[x][y] = True
dfs(x + 1, y, tmp + board[x][y])
dfs(x - 1, y, tmp + board[x][y])
dfs(x, y + 1, tmp + board[x][y])
dfs(x, y - 1, tmp + board[x][y])
vis[x][y] = False
rowLength, colLength, flag = len(board), len(board[0]), False
vis = [[False for _ in range(colLength)] for _ in range(rowLength)]
for i in range(rowLength):
for j in range(colLength):
if board[i][j] == word[0]:
dfs(i, j, '')
if flag:
return flag
return flag