Leetcode79. Word Search
Leetcode79. Word Search
完成Leetcode212. Word Search II后,简化版的Leetcode79. Word Search改写一下程序就可以完成
题目
思路
对board中的每个字母,进行dfs遍历,检查是否与word match
也可以沿用Leetcode212. Word Search II的思路,将单个单词建成Trie,这样比较通用
复杂度
设词的长度为L,board有M行N列
-
时间复杂度 O ( n ) \mathcal{O}(n) O(n)
最坏情况,board中的每个字母,向四个方向都能不停的匹配下去,直到达到单词长度,如单词为aaaaaa,board中字母也全是a,则时间复杂度为 O ( 4 ∗ L ∗ M ∗ N ) = O ( L ∗ M ∗ N ) \mathcal{O}(4*L*M*N)=\mathcal{O}(L*M*N) O(4∗L∗M∗N)=O(L∗M∗N)
最好情况,board中的每个字母,都没有匹配到起点, O ( M ∗ N ) \mathcal{O}(M*N) O(M∗N) -
空间复杂度 O ( M ∗ N ) \mathcal{O}(M*N) O(M∗N)
board占用 O ( M ∗ N ) \mathcal{O}(M*N) O(M∗N)
代码
class Solution:
def exist(self, board, word: str) -> bool:
if not board or not word:
return False
m = len(board)
n = len(board[0])
self.match = False
def search(index, i, j):
c = board[i][j]
w = word[index]
if not c == w: # 不匹配
return
if c == w and index == len(word) - 1: # 说明word匹配完毕
self.match = True
return
board[i][j] = '' # 防止从o访问到a后,又回头访问o
# 向四个方向搜索
if i > 0:
search(index + 1, i - 1, j)
if j > 0:
search(index + 1, i, j - 1)
if i < m - 1:
search(index + 1, i + 1, j)
if j < n - 1:
search(index + 1, i, j + 1)
board[i][j] = c
for i in range(m):
for j in range(n):
search(0, i, j)
return self.match