leetcode 第79题,图上的深搜题。
第一步,先要写个遍历循环,找到搜索的起点,也就是首字母。
第二步,从起点出发开始搜索,搜索时主要要记录已经走过的地方,这里可以使用一个二维的数组单独来记录,或者走过的地方标识为‘#’,搜索后恢复这个位置的字符。
注意,每次搜索时,都要比较word和当前路径已经遍历到的字符,这里可以使用增量式的比较方法,每次比较一个字符即可。
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
row = len(board)
col = len(board[0])
def dfs(current_x, current_y, board, index, word):
if index == len(word)-1:
return True
tmp = board[current_x][current_y]
board[current_x][current_y] = '#'
if current_x+1 < row and board[current_x+1][current_y] == word[index+1]:
if dfs(current_x+1, current_y, board, index+1, word):
return True
if current_x-1 >= 0 and board[current_x-1][current_y] == word[index+1]:
if dfs(current_x-1, current_y, board, index+1, word):
return True
if current_y+1 < col and board[current_x][current_y+1] == word[index+1]:
if dfs(current_x, current_y+1, board, index+1, word):
return True
if current_y-1 >= 0 and board[current_x][current_y-1] == word[index+1]:
if dfs(current_x, current_y-1, board, index+1, word):
return True
board[current_x][current_y] = tmp
return False
for i in range(row):
for j in range(col):
if board[i][j] == word[0]:
if dfs(i, j, board, 0, word):
return True
return False