212. Word Search II
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
rows = len(board)
cols = len(board[0])
directions = [(1,0),(-1,0),(0,1),(0,-1)]
def backtrack(r, c, word):
if len(word) == 0:
return True
if 0 <= r < rows and 0 <= c < cols and board[r][c] == word[0]:
board[r][c] = '#'
for dr, dc in directions:
if backtrack(r+dr, c+dc, word[1:]):
board[r][c] = word[0]
return True
board[r][c] = word[0]
return False
ans = set()
for word in set(words):
for r in range(rows):
for c in range(cols):
if backtrack(r, c, word):
ans.add(word)
return ansTrie
第一步
第二步
第三步
Last updated