开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第25天,点击查看活动详情
212.单词搜索II
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/wo…
给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例 1:
输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] 输出:["eat","oath"]
示例 2:
输入:board = [["a","b"],["c","d"]], words = ["abcb"] 输出:[]
提示:
- m == board.length
- n == board[i].length
- 1 <= m, n <= 12
- board[i][j] 是一个小写英文字母
- 1 <= words[i].length <= 10
- words[i] 由小写英文字母组成
- words 中的所有字符串互不相同
解法
字典树+回溯算法dfs
- python
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
if board is None or words is None or len(board) < 1 and len(words) < 1:
return []
tries = {}
for word in words:
t = tries
for w in word:
if w not in t:
t[w] = {}
t = t[w]
t['end'] = 1
print(tries)
rows = len(board)
cols = len(board[0])
res = []
def dfs(i, j, tries, s):
c = board[i][j]
if c not in tries:
return
trie = tries[c]
if 'end' in trie and trie['end'] == 1:
res.append(s+c)
trie['end'] = 0
board[i][j] = "#"
for x, y in [[-1, 0], [1, 0], [0, 1], [0, -1]]:
tmp_x = x + i
tmp_y = y + j
if 0 <= tmp_x < rows and 0 <= tmp_y < cols and board[tmp_x][tmp_y] != '#':
dfs(tmp_x, tmp_y, trie, s + c)
board[i][j] = c
for i in range(rows):
for j in range(cols):
dfs(i, j, tries, "")
return res
复杂度分析
- 时间复杂度:O(n),其中 n 是数组nums 的长度。
- 空间复杂度:O(1)