题目描述
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" 输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" 输出:false
思路
深度优先遍历(dfs)+ 回溯
需要用到一个mark数组来标记是否走过
class Solution(object):
def __init__(self):
self.direction = [(0,1),(-1,0),(1,0),(0,-1)]
def backtrack(self,i,j,board,word,mark):
if len(word)==0:
return True
for dir in self.direction:
cur_i = i+dir[0]
cur_j = j+dir[1]
if cur_i>=0 and cur_i<len(board) and cur_j>=0 and cur_j<len(board[0]) and board[cur_i][cur_j]==word[0]:
if mark[cur_i][cur_j]==1: # 如果已经标记为使用过,则continue
continue
mark[cur_i][cur_j]=1
if self.backtrack(cur_i,cur_j,board,word[1:],mark)==True:
return True
else:
mark[cur_i][cur_j]=0
return False
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
rows = len(board)
cols = len(board[0])
mark = [[0]*cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
if board[i][j] == word[0]:
mark[i][j] = 1
if self.backtrack(i,j,board,word[1:],mark)==True:
return True
else:
mark[i][j]=0
return False
if __name__ == "__main__":
s=Solution()
board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]]
word = "ABCCED"
print(s.exist(board, word))