https://leetcode.com/problems/word-search/
2020/08/16
一题经典的宽搜,没有什么难点。用二维vis数组防止回头,退出的时候要记得把那个格子的vis重新设成0。
我的源代码search函数里面return的True和False是没必要的,但是懒得改了。
如果需要输出路径的话,可以用global变量记录路径,也可以对search函数多加母i,j的变量(这样用的内存少一些)。
class Solution:
board = [[]]
word = ''
m = 0
n = 0
flag = False
def exist(self, board: List[List[str]], word: str) -> bool:
if len(word) == 0:
return False
self.board = board
self.word = word
self.m = len(board)
self.n = len(board[0])
self.flag = False
for i in range(self.m):
for j in range(self.n):
if self.board[i][j] == self.word[0]:
self.flag = False
vis = [[0 for p in range(self.n)] for q in range(self.m)]
self.search(i, j, 0, vis)
if self.flag == True:
return True
return False
def search(self, i, j, ltr, vis):
if self.flag == True:
return True
vis[i][j] = 1
if ltr == len(self.word) - 1:
if self.word[ltr] == self.board[i][j]:
self.flag = True
return True
return False
if self.word[ltr] != self.board[i][j]:
return False
nxt = []
for (di, dj) in [(-1,0),(1,0),(0,1),(0,-1)]:
if di == 0 and dj == 0:
continue
if self.judge(i+di, j+dj, self.word[ltr+1]) and vis[i+di][j+dj] == 0:
nxt.append((i+di, j+dj))
for t in nxt:
(newi, newj) = t
self.search(newi, newj, ltr+1, vis)
vis[newi][newj] = 0
def judge(self, i, j, x):
if i < 0 or i > self.m - 1 or j < 0 or j >self.n - 1:
return False
if self.board[i][j] == x:
return True
return False