1. 每一步递归中,都要注意判断 start_x,start_y的取值范围
2. 学到了python里面的语法还可以直接大于小于判断。
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