给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
【中等】
【分析】
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not word:
return True
seen=[[0 for j in range(len(board[0]))]for i in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if self.backtrack(board,word,0,i,j,seen):
return True
return False
def backtrack(self,board,word,index,i,j,seen):
if index==len(word)-1:
return board[i][j]==word[index]
if board[i][j]==word[index]:
seen[i][j]=1
next_index=[(i-1,j),(i+1,j),(i,j-1),(i,j+1)] #左,右,上,下
for next_i,next_j in next_index:
if 0<=next_i<len(board) and 0<=next_j<len(board[0])\
and seen[next_i][next_j]==0\
and self.backtrack(board,word,index+1,next_i,next_j,seen):
return True
seen[i][j]=0
return False