一、题目
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
说明:
你可以假设所有输入都由小写字母 a-z 组成。
提示:
- 你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
- 如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。什么样的数据结构可以有效地执行这样的操作?散列表是否可行?为什么? 前缀树如何?如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。
二、解决
1、暴力DFS
思路:
遍历二维数组,对每一个字符进行DFS,如果遍历的结果在给出的words列表中,则该word加入到返回结果中。
代码:
这里略,详细可查看详细通俗的思路分析,多解法。
时间复杂度: O ( M ∗ ( 4 ∗ 3 L − 1 ) O(M*(4*3^{L-1}) O(M∗(4∗3L−1),M为单元格数,L为单词最大长度。
空间复杂度: O ( N ) O(N) O(N),字典中字母总数。
2、Trie+DFS
版本1
思路:
1.1 Trie树
关于Trie的数据结构与常见操作实现请先看【LeetCode】208. 实现 Trie (前缀树)
1.2 DFS模板
voidDFS ( Vertex V )
{
visited[V] = true;
for( V 的每个邻接点W )
if( !visited[W] )
DFS( W );
}
1.3 过程
先遍历words形成相应的Trie树,然后遍历给出的二维字符数组board,逐行遍历,对于每一个字符,判断其是否在Trie树中,如果在,则向四周进行DFS,符合加入返回结果;如果不在,则跳过,到下一个字符,继续进行DFS,直到board遍历结束。
代码:
本题代码的编写在【LeetCode】208. 实现 Trie (前缀树)代码的基础上实现。
class TrieNode {
boolean isEnd;
Map<Character, TrieNode> next = new HashMap<>();
}
class Trie {
TrieNode root = new TrieNode();
public Trie() {
}
public void insert(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
if (!curr.next.containsKey(c)) {
TrieNode tmp = new TrieNode();
curr.next.put(c, tmp);
}
curr = curr.next.get(c);
}
curr.isEnd = true;
}
public boolean search(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
if (!curr.next.containsKey(c)) return false;
curr = curr.next.get(c);
}
return curr.isEnd;
}
public boolean startsWith(String prefix) {
TrieNode curr = root;
for (char c : prefix.toCharArray()) {
if (!curr.next.containsKey(c)) return false;
curr = curr.next.get(c);
}
return true;
}
}
class Solution {
private Set<String> res = new HashSet<>();
private int rows, cols;
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String word : words) {
trie.insert(word);
}
rows = board.length; cols = board[0].length;
boolean[][] visited = new boolean[rows][cols];
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
DFS(board, trie, visited, "", row, col);
}
}
return new ArrayList<String>(res);
}
public void DFS(char[][] board, Trie trie, boolean[][] visited, String str, int row, int col) {
if (row<0 || row>=rows || col<0 || col>=cols) return;
if (visited[row][col]) return;
str += board[row][col];
if (!trie.startsWith(str)) return;
if (trie.search(str)) {
res.add(str);
}
visited[row][col] = true;
DFS(board, trie, visited, str, row+1, col);
DFS(board, trie, visited, str, row-1, col);
DFS(board, trie, visited, str, row, col+1);
DFS(board, trie, visited, str, row, col-1);
visited[row][col] = false;
}
}
时间复杂度: O ( M ∗ ( 4 ∗ 3 L − 1 ) O(M*(4*3^{L-1}) O(M∗(4∗3L−1),M为单元格数,L为单词最大长度。
空间复杂度: O ( N ) O(N) O(N),字典中字母总数。
版本2
思路: 同版本1。
代码:
对版本1略作简化,如下:
class Solution {
// Trie Node
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word;
}
// build the trie from words array
public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode current = root;
for (char c : w.toCharArray()) {
int i = c - 'a'; // index adjustment
if (current.children[i] == null)
current.children[i] = new TrieNode();
current = current.children[i];
}
current.word = w; // assign word w to word of trie node
}
return root;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<>();
// build the trie from using dictionary words.
TrieNode root = buildTrie(words);
// call the dfs
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs(board, i, j, root, result);
}
}
return result;
}
public void dfs(char[][] board, int i, int j, TrieNode root, List<String> result) {
char c = board[i][j]; // get the current character from the board at i, j
if (c == '*' || root.children[c - 'a'] == null)
return;
root = root.children[c - 'a'];
if (root.word != null) {
// found one words add in the result list
result.add(root.word);
root.word = null; // de-duplicate remove the word from trie
}
board[i][j] = '*'; // update the character of at i , j no need for visited array
if (i > 0) dfs(board, i - 1, j, root, result); // up
if (j > 0) dfs(board, i, j - 1, root, result); // left
if (i < board.length - 1) dfs(board, i + 1, j, root, result); // down
if (j < board[0].length - 1) dfs(board, i, j + 1, root, result); // right
board[i][j] = c; // backtrack the character
}
}
时间复杂度: O ( M ∗ ( 4 ∗ 3 L − 1 ) O(M*(4*3^{L-1}) O(M∗(4∗3L−1),M为单元格数,L为单词最大长度。
空间复杂度: O ( N ) O(N) O(N),字典中字母总数。
三、参考
1、Java 15ms Easiest Solution (100.00%)
2、Two Solution | Trie DFS Backtracking | Steps & Well commented
3、My simple and clean Java code using DFS and Trie
4、单词搜索 II
5、详细通俗的思路分析,多解法