[Leetcode]79. Word Search
79. Word Search
- 本题难度: Medium
- Topic: DFS
Description
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.
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.
我的代码
class Solution:
def exist(self, board: 'List[List[str]]', word: 'str') -> 'bool':
#DFS
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
state = [[False for _ in range(len(board[0]))] for _ in range(len(board))]
if self.dfs(board,state,word,i,j):
return True
return False
def dfs(self, board, state, word,x,y):
op_x = [1, -1, 0, 0]
op_y = [0, 0, 1, -1]
if word == '':
return True
if x<0 or x >= len(board) or y<0 or y >= len(board[0]) or state[x][y] == True or board[x][y] != word[0]:
return False
state[x][y] = True
res = False
for i in range(4):
res = res or self.dfs(board, state, word[1:],x+op_x[i],y+op_y[i])
#忘记了超级重要的!!
#因为state是全局变量!!
#对于上一层来说 之前改变的state应该消除
state[x][y] = False
return res
别人的代码
Python dfs solution with comments
这里没有使用state来标柱是否走过,而是选择用不可能有单词会用的‘#’来临时修改。很巧妙。
def exist(self, board, word):
if not board:
return False
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if self.dfs(board, i, j, word):
return True
return False
# check whether can find word, start at (i,j) position
def dfs(self, board, i, j, word):
if len(word) == 0: # all the characters are checked
return True
if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:
return False
tmp = board[i][j] # first character is found, check the remaining part
board[i][j] = "#" # avoid visit agian
# check whether can find "word" along one direction
res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \
or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])
board[i][j] = tmp
return res
思路
1.
因为是能否找到的问题,所以使用来DFS。
2.
记得要把状态改回来。因为在深度优先的时候,可能会出现最后找不到这个单词,但是它使用过的字母可以给它兄弟结点的情况使用。
- 时间复杂度 O((mxn)^2)
- 出错 忘记把状态改回来了。