和WordSearchII 思路和结构都很相似,唯一的就是 单个词搜索时就是 按 letter index 来搜(Trie的话就是 一层一层: next[index] == None ?)
代码一次通过!
自己的思路: 每次 index+1 来递归
别人的思路:每次 word = word[1:], 掐掉首字母(index always be 0)
代码如下:
from typing import List
class Solution(object):
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board)
n = len(board[0])
# with my solution defined
# # Bug: for i in m: Too rush!!!
# for i in range(m):
# for j in range(n):
# tag = [False]
# self.dfs(i, j, board, word, 0, tag)
# if tag[0] is True:
# return True
# with other's solution considered
for i in range(m):
for j in range(n):
if self.dfs(i, j, board, word) is True:
return True
return False
# My solution
# def dfs(self, i: int, j: int, board: List[List[str]], word: str, curr_index: int, tag: List[bool]):
# if curr_index == len(word):
# tag[0] = True
# return
#
# m = len(board)
# n = len(board[0])
# if i < 0 or i >= m or j < 0 or j >= n:
# return
#
# cell_letter = board[i][j]
# if cell_letter == "#" or cell_letter != word[curr_index]:
# return
#
# board[i][j] = "#"
#
# # any function call, even recursive call (calling oneself), need to add self, this is like finding the namespace
# self.dfs(i - 1, j, board, word, curr_index + 1, tag)
# self.dfs(i + 1, j, board, word, curr_index + 1, tag)
# self.dfs(i, j - 1, board, word, curr_index + 1, tag)
# self.dfs(i, j + 1, board, word, curr_index + 1, tag)
#
# board[i][j] = cell_letter
# Another solution - considering the solution of others:
# https://leetcode.com/problems/word-search/discuss/27660/Python-dfs-solution-with-comments.
def dfs(self, i: int, j: int, board: List[List[str]], word: str):
if 0 == len(word):
return True
m = len(board)
n = len(board[0])
if i < 0 or i >= m or j < 0 or j >= n:
return
cell_letter = board[i][j]
if cell_letter == "#" or cell_letter != word[0]:
return
board[i][j] = "#"
# any function call, even recursive call (calling oneself), need to add self, this is like finding the namespace
new_word = word[1:]
res = self.dfs(i - 1, j, board, new_word) or \
self.dfs(i + 1, j, board, new_word) or \
self.dfs(i, j - 1, board, new_word) or \
self.dfs(i, j + 1, board, new_word)
board[i][j] = cell_letter
return res
def main():
solution = Solution()
board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]]
word = "ABCCED"
print(solution.exist(board, word))
if __name__ == "__main__":
main()