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','E','S'], ['A','D','E','E'] ] Given word = "SEE", return true. Given word = "ABCB", return false.
这一道题很像LeetCode200. Number of Islands,需要利用dfs解决,但是实际上更难一些,不能单纯的用一个visited矩阵或是刷新visited矩阵来记录是否访问过某个字母,因为有的情况下第一次访问的数字不能用,但是绕一圈就可以用了。
比如上面的例子中(有修改)“ABCESEEEF”时候,[1,2]的“E”第一次遍历用不上,之后就用上了。
这种修改的方式就是设置临时变量,记录当前字母,然后将当前字母修改进行标记,最后在遍历结束后重新赋值,改为原来的字母。
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not board:return None
self.board = board
self.row, self.col = len(board), len(board[0])
self.boolean=False
for i in range(self.row):
for j in range(self.col):
if board[i][j]==word[0] and not self.boolean:
self.dfs(i,j,word)
return self.boolean
def dfs(self,i,j,word):
if i<0 or j<0 or i>=self.row or j>=self.col or self.boolean or self.board[i][j]!=word[0]:
return
temp=self.board[i][j]
self.board[i][j]='#'
word=word[1:]
if len(word)==0:self.boolean=True
self.dfs(i-1,j,word)
self.dfs(i+1,j,word)
self.dfs(i,j-1,word)
self.dfs(i,j+1,word)
self.board[i][j]=temp
这里为了记录有符合条件的情况时返回最后结果,我用了self.来记录。
看到discuss里用return or or or这种方式,值得学习。
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