Leetcode 97. Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
思路: 很典型的DFS题目,和二维迷宫类似。扫描board,如果当前的board[i][j] == word[0],那么dfs 扫描 上下左右的四个位置是不是满足 board[x-1][y] == word[0] (注意这里的word已经被word[1:0]替代)。在dfs的过程中,如果发现len(word) == 0, return True. 否则最后return False。
注意本题中pop是用L22-L25来实现的,先将这个位置的数字保存下来,并将其赋值成#,如果L23中的dfs不返回True。那么说明这条路走不通,这是我们需要将board[x][y]的值再改回tmp。
1 class Solution(object): 2 def exist(self, board, word): 3 """ 4 :type board: List[List[str]] 5 :type word: str 6 :rtype: bool 7 """ 8 for i in range(len(board)): 9 for j in range(len(board[0])): 10 if board[i][j] == word[0]: 11 if self.dfs(i, j, board, word[1:]): 12 return True 13 return False 14 15 def dfs(self, x, y, board, word): 16 if len(word) == 0: 17 return True 18 19 20 if x > 0 and board[x-1][y] == word[0]: 21 tmp = board[x][y] 22 board[x][y] = '#' 23 if self.dfs(x-1,y, board, word[1:]): 24 return True 25 board[x][y] = tmp 26 27 if x < len(board)-1 and board[x+1][y] == word[0]: 28 tmp = board[x][y] 29 board[x][y] = '#' 30 if self.dfs(x+1,y, board, word[1:]): 31 return True 32 board[x][y] = tmp 33 34 if y > 0 and board[x][y-1] == word[0]: 35 tmp = board[x][y] 36 board[x][y] = '#' 37 if self.dfs(x,y-1, board, word[1:]): 38 return True 39 board[x][y] = tmp 40 41 if y < len(board[0])-1 and board[x][y+1] == word[0]: 42 tmp = board[x][y] 43 board[x][y] = '#' 44 if self.dfs(x,y+1, board, word[1:]): 45 return True 46 board[x][y] = tmp 47 48 return False 49