给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
想法:本题跟我们9021 quiz7-8的类型是一样的,9024也用C写过一次,都是在二维数组里搜索,用回溯算法,今天脑袋有点不清醒,以后多刷几次。
学到的点:
1. 每一步递归中,都要注意判断 start_x,start_y的取值范围
2. 学到了python里面的语法还可以直接大于小于判断。
if 0<=start_x<noOfRow and 0<=start_y<noOfCol
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
noOfRow = len(board)
noOfCol = len(board[0])
visited = [[False for _ in range(noOfCol)] for _ in range(noOfRow)]
for i in range(noOfRow):
for j in range(noOfCol):
if self.helper(i,j,board,visited,noOfRow,noOfCol,0,word):
print(i,j)
return True
return False
def helper(self,start_x,start_y,board,visited,noOfRow,noOfCol,point,word):
directions = [(0,1),(1,0),(0,-1),(-1,0)]
if point == len(word)-1:
if 0<=start_x<noOfRow and 0<=start_y<noOfCol and board[start_x][start_y] == word[point] and not visited[start_x][start_y]:
return True
else:
return False
if 0<=start_x<noOfRow
and 0<=start_y<noOfCol and board[start_x][start_y] == word[point] and point<len(word) and not visited[start_x][start_y]:
visited[start_x][start_y] = True
for direction in directions:
new_x = start_x + direction[0]
new_y = start_y + direction[1]
if self.helper(new_x,new_y,board,visited,noOfRow,noOfCol,point+1,word):
return True
visited[start_x][start_y] = False
return False