Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false.
测试用例
1 2 3 4 5 6 7 8 9 10 11
board = [ ['A','B','C','E'], ['S','F','A','S'], ['A','E','F','E'] ] # Case 0: word is an empty string, word = '', returnfalse # Case 1: genaral case - word = "ABFE", returntrue # Case 2: take backtracking under advisement, word = "AEFBCAFE", returntrue. # Case 3: word = "ADEF", returnfalse
visited = set() defdfs(x, y, d): if out_of_bound(x, y): returnFalse if (x, y) in visited: returnFalse if board[x][y] != word[d]: returnFalse if d == len(word) - 1: returnTrue
visited = set() defdfs(x, y, d): if out_of_bound(x, y): returnFalse if (x, y) in visited: returnFalse if board[x][y] != word[d]: returnFalse if d == len(word) - 1: returnTrue # continue dfs visited.add((x,y)) dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] found = False for i inrange(4): new_x = x + dx new_y = y + dy found = found or dfs(new_x, new_y, d+1) return found
visited = set() defdfs(x, y, d): if out_of_bound(x, y): returnFalse if (x, y) in visited: returnFalse if board[x][y] != word[d]: returnFalse if d == len(word) - 1: returnTrue # continue dfs visited.add((x,y)) dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] found = False for i inrange(4): new_x = x + dx new_y = y + dy found = found or dfs(new_x, new_y, d+1) ifnot found: visited.remove((x, y)) return found
代码实现
根据如上分析,代码实现如下(实现使用 used 数组保存访问过的坐标,和用集合 visited 功能一致):
classSolution: defexist(self, board: List[List[str]], word: str) -> bool: ifnot board ornot word: returnFalse m, n = len(board), len(board[0]) used = [[False] * n for _ inrange(m)] defdfs(x, y, pos): # x, y out of bound if x < 0or x >= m or y < 0or y >= n: returnFalse # word[pos] not equals to board[x][y] if word[pos] != board[x][y]: returnFalse # (x, y) already used if used[x][y]: returnFalse # pos == len(word)-1 if pos == len(word) - 1: returnTrue
found = False for i inrange(4): new_x = x + dx[i] new_y = y + dy[i] found = found or dfs(new_x, new_y, pos+1) # backtrack ifnot found: used[x][y] = False return found
for i inrange(m): for j inrange(n): if dfs(i, j, 0): returnTrue returnFalse
classSolution: defexist(self, board: List[List[str]], word: str) -> bool: ifnot board ornot word: returnFalse m, n = len(board), len(board[0]) defdfs(x, y, pos): # x, y out of bound if x < 0or x >= m or y < 0or y >= n: returnFalse # word[pos] not equals to board[x][y] if word[pos] != board[x][y]: returnFalse # pos == len(word)-1 if pos == len(word) - 1: returnTrue
found = False for i inrange(4): new_x = x + dx[i] new_y = y + dy[i] found = found or dfs(new_x, new_y, pos+1) # backtrack board[x][y] = orignal return found
for i inrange(m): for j inrange(n): if dfs(i, j, 0): returnTrue returnFalse