Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example 1:

Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] Output: ["eat","oath"]
Example 2:

Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Constraints:
m == board.lengthn == board[i].length1 <= m, n <= 12board[i][j]is a lowercase English letter.1 <= words.length <= 3 * 1041 <= words[i].length <= 10words[i]consists of lowercase English letters.- All the strings of
wordsare unique.
ChatGPT's Solution:
class TrieNode: def __init__(self): self.children = {} self.is_word = False class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: # Build Trie from words def build_trie(words): root = TrieNode() for word in words: node = root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_word = True return root # Backtracking DFS function to search for words def dfs(board, node, i, j, path): # Check boundaries and if current position is already visited or doesn't match if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or board[i][j] == '#': return char = board[i][j] if char not in node.children: return # Mark the cell as visited board[i][j] = '#' node = node.children[char] path += char # If we found a valid word, add it to the result if node.is_word: result.add(path) # Explore the 4 adjacent cells dfs(board, node, i + 1, j, path) dfs(board, node, i - 1, j, path) dfs(board, node, i, j + 1, path) dfs(board, node, i, j - 1, path) # Un mark the cell for the next exploration board[i][j] = char # Main part of the algorithm trie_root = build_trie(words) result = set() for i in range(len(board)): for j in range(len(board[0])): dfs(board, trie_root, i, j, '') return list(result)

Explanation:
-
TrieNode Class: A basic Trie node that stores the children nodes and a boolean flag
is_wordto mark if the node represents the end of a word. -
build_trie(): Builds a Trie from the list of words.
-
dfs(): Performs Depth-First Search (DFS) to explore adjacent cells on the board. If the current cell matches the next character of a word, the search continues. If a complete word is found, it's added to the result set.
-
Main Loop: The main function iterates over the board, and for each cell, calls
dfsto search for words starting from that cell.

浙公网安备 33010602011771号