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,
Given words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"].
Code
class TrieNode {
boolean end;
Map<Character, TrieNode> sons;
String s;
public TrieNode() {
sons = new HashMap<>();
}
}
class Trie {
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert (String s) {
if (s == null || s.length() == 0) return;
TrieNode node = root;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!node.sons.containsKey(c)) {
TrieNode newNode = new TrieNode();
node.sons.put(c, newNode);
}
node = node.sons.get(c);
}
node.end = true;
node.s = s;
}
public boolean search(String s) {
if (s == null || s.length() == 0) return true;
TrieNode node = root;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (node.sons.containsKey(c)) {
node = node.sons.get(c);
} else {
return false;
}
}
return node.end;
}
}
public class Solution {
private int[] dx = {1, 0, -1, 0};
private int[] dy = {0, 1, 0, -1};
private Trie t;
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<>();
t = new Trie();
for (String word: words) {
t.insert(word);
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
search(board, i, j, t.root, result);
}
}
return result;
}
public void search(char[][] board, int x, int y, TrieNode node, List<String> result) {
if (node.end) {
if (!result.contains(node.s)) {
result.add(node.s);
}
}
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || board[x][y] == 0 || node == null) return;
if (node.sons.containsKey(board[x][y])) {
for (int i = 0; i < 4; i++) {
char c = board[x][y];
board[x][y] = 0;
search(board, x + dx[i], y + dy[i], node.sons.get(c), result);
board[x][y] = c;
}
}
}
}
Solution
用字典树实现。讲所有字符串加进字典树。DFS遍历board,将符合条件的字符串加入结果集中。