Amazon VO 面试真题解析:Word Search Collection(字典树 + DFS)

13次阅读
没有评论

Word Search Collection

Given a grid of letters and a list of words, return all words from the list that can be formed in the grid.

Words can be formed by connecting adjacent letters horizontally or vertically, not diagonally.

Each cell in the grid can only be used once per word.

Example Grid:

[['d', 'o', 'g', 's'],
  ['c', 'a', 't', 'p'],
  ['b', 't', 'a', 'r'],
  ['h', 'e', 'n', 's']
]

Word List: [“cats”, “dog”, “hen”, “star”, “tap”, “rat”, “spa”, “net”]

Expected Output: [“dog”, “hen”, “rat”, “net”]

Write a function findWords(grid, wordList) that returns an array of all words from wordList found in the grid.

这道题是典型的单词搜索变体,核心思路通常是把词库先构造成字典树(Trie),再在网格上按格子做深度优先搜索(DFS)和回溯。因为题目要求返回列表中所有能在二维字符网格中通过上下左右相邻连接形成的单词,而且每个格子每个单词只能使用一次,所以用 Trie 可以在搜索过程中快速剪枝,避免对每个单词单独暴力匹配。示例中像 dog、hen、rat、net 都能被找到,而 cats、star、spa 无法按规则拼出。整体上,这是一个用 Trie + DFS 解决多模式匹配的经典在线评测题。

正文完
 0