212 Word Search II

1. Question

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.
For example, Givenwords=["oath","pea","eat","rain"]andboard=
1
[
2
['o','a','a','n'],
3
['e','t','a','e'],
4
['i','h','k','r'],
5
['i','f','l','v']
6
]
Copied!
Return
["eat","oath"].
Note: You may assume that all inputs are consist of lowercase lettersa-z.
hint:
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem:Implement Trie (Prefix Tree)first.

2. Implementation

(1) Trie + Backtracking
1
class Solution {
2
class TrieNode {
3
char val;
4
boolean isWord;
5
TrieNode childNode[];
6
7
public TrieNode() {
8
childNode = new TrieNode[26];
9
}
10
}
11
12
class Trie {
13
TrieNode root;
14
15
public Trie() {
16
root = new TrieNode();
17
}
18
19
public void add(String word) {
20
if (word == null || word.length() == 0) {
21
return;
22
}
23
24
TrieNode curNode = root;
25
26
for (char c : word.toCharArray()) {
27
int index = c - 'a';
28
29
if (curNode.childNode[index] == null) {
30
curNode.childNode[index] = new TrieNode();
31
curNode.val = c;
32
}
33
curNode = curNode.childNode[index];
34
}
35
curNode.isWord = true;
36
}
37
}
38
39
public List<String> findWords(char[][] board, String[] words) {
40
List<String> res = new ArrayList<>();
41
42
if (board == null || board.length == 0 || words == null || words.length == 0) {
43
return res;
44
}
45
46
Trie trie = new Trie();
47
48
for (String word : words) {
49
trie.add(word);
50
}
51
52
int m = board.length, n = board[0].length;
53
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
54
55
StringBuilder word = new StringBuilder();
56
57
for (int i = 0; i < m; i++) {
58
for (int j = 0; j < n; j++) {
59
searchWord(i, j, trie.root, word, words, directions, board, res);
60
}
61
}
62
return res;
63
}
64
65
public void searchWord(int row, int col, TrieNode node, StringBuilder word, String[] words, int[][] directions, char[][] board, List<String> res) {
66
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] == '#') {
67
return;
68
}
69
70
char c = board[row][col];
71
TrieNode curNode = node.childNode[c - 'a'];
72
73
if (curNode == null) {
74
return;
75
}
76
77
word.append(c);
78
79
if (curNode.isWord) {
80
curNode.isWord = false;
81
res.add(word.toString());
82
}
83
84
board[row][col] = '#';
85
86
for (int[] direction : directions) {
87
int nextRow = row + direction[0];
88
int nextCol = col + direction[1];
89
searchWord(nextRow, nextCol, curNode, word, words, directions, board, res);
90
}
91
board[row][col] = c;
92
word.setLength(word.length() - 1);
93
}
94
}
Copied!

3. Time & Space Complexity

时间复杂度O(kL) + O(mn * 4 ^ L), k是word的个数, L是每个word的平均长度, kl是建立trie的时间。我们的回溯算法对每个board的格子都遍历一遍,每个格子有4个方向可以走,知道走到word的长度为止,所以遍历的时间是mn * 4 ^ L,空间复杂度O(26*L) 主要是trie的空间