leetcode 212 Word Search II
z

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:

1
2
3
4
5
6
7
8
9
10
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"]

Note:

  1. All inputs are consist of lowercase letters a-z.
  2. The values of words are distinct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65


class Solution {
class TrieNode{
TrieNode[] next;
boolean isWord;
public TrieNode() {
next = new TrieNode[26];
};
}

public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String s: words) {
TrieNode p = root;
for (char c: s.toCharArray()) {
if (p.next[c-'a'] == null) {
p.next[c-'a'] = new TrieNode();
}
p = p.next[c-'a'];
}
p.isWord = true;
}
return root;
}

public List<String> findWords(char[][] board, String[] words) {
List<String> ans = new LinkedList<>();
if (board.length == 0 || board[0].length == 0 || words.length == 0) return ans;
TrieNode root = buildTrie(words);
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
StringBuilder sb = new StringBuilder();
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
helper(ans, sb, root, i, j, m, n, visited, board);
}
}
return ans;
}
public void helper(List<String> ans, StringBuilder sb, TrieNode root, int i, int j, int m, int n, boolean[][] visited, char[][] matrix) {

if (root == null) return ;

if (root.isWord) {
ans.add(sb.toString());
root.isWord = false; // 这里不用终止
}

if (i<0 || j<0 || i>=m || j >=n || visited[i][j])
return ;

visited[i][j] = true;
char c = matrix[i][j];
sb.append(c);
helper(ans, sb, root.next[c-'a'], i-1, j, m, n, visited, matrix);
helper(ans, sb, root.next[c-'a'], i+1, j, m, n, visited, matrix);
helper(ans, sb, root.next[c-'a'], i, j-1, m, n, visited, matrix);
helper(ans, sb, root.next[c-'a'], i, j+1, m, n, visited, matrix);
sb.deleteCharAt(sb.length()-1);
visited[i][j] = false;

}
}