Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Example

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

Output: ["eat","oath"]

You may assume that all inputs are consist of lowercase lettersa-z.

Note

与前置题目不同的是,这里需要返回给定words集合的所有包含在2D board的单词

这里使用trie进行剪枝,insert方法把所有待查找的单词插入trie中,search方法判断是否在trie中,startWith方法判断是否为前缀

递归和前置题目类似,搜索2D board的所有元素,给出一个通俗版本,返回结果可以用set去重,问题不大,当然还可以极限提速度。。 见 https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)

Time: O(m * n * wl * 4^wl) -> O(m * n * 4^wl) wl is the average length of words

Space: O(cnt * wl) cnt is the number of words

Code

Last updated