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"]. Note: You may assume that all inputs are consist of lowercase letters a-z.
click to show 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.
Solution
public class Solution {
public class Node {
public Node[] child;
public boolean end;
public boolean includedInAns;
public String here;
public Node() {
child = new Node[26];
end = false;
here = null;
includedInAns = false;
}
}
public List<String> findWords(char[][] board, String[] words) {
Node root = new Node();
for(String word: words) {
Node iter = root;
for(char c: word.toCharArray()) {
if(iter.child[c-'a'] == null) iter.child[c-'a'] = new Node();
iter = iter.child[c-'a'];
}
iter.end = true;
iter.here = word;
}
int m = board.length;
int n = board[0].length;
List<String> ans = new ArrayList<String>();
boolean used[][] = new boolean[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
// enumarate all starting points
dfs(ans, board, used, root, i, j);
}
}
return ans;
}
public void dfs(List<String> ans, char[][] board, boolean used[][], Node iter, int i, int j) {
// current node is iter, try the position i j
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || used[i][j]) {
return;
} else {
// try to walk a step
char c = board[i][j];
if(iter.child[c-'a'] != null) {
iter = iter.child[c-'a'];
if(iter.end && !iter.includedInAns) {
ans.add(iter.here);
iter.includedInAns = true;
}
// try to walk in other four directions
used[i][j] = true;
dfs(ans, board, used, iter, i - 1, j);
dfs(ans, board, used, iter, i + 1, j);
dfs(ans, board, used, iter, i, j - 1);
dfs(ans, board, used, iter, i, j + 1);
used[i][j] = false;
}
}
}
}