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"]
.
这个题是79题的变种,当时看到我的第一想法是无非就是从判断一个词变成判断多个词,怎么难度就变成Hard了?拿79题的代码简单改改一提交,果然超时了,一看测试用例我去真复杂。看来原来的思路是不能用了,但是新的思路又想不出来,只能看提示,发现是要用前缀树,但是还是一脸蒙逼,毫无头绪。只能上网查有关资料,看到前缀树的几个应用才大概明白了思路。总之这个题和79题个人感觉出的还是很不错的,能让人很好的理解递归和前缀树。代码如下(注意前缀树的构造和它在这个题的解决算法中的应用思路):
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
char[][] board = new char[][] { { 'o', 'a', 'a', 'n' },
{ 'e', 't', 'a', 'e' }, { 'i', 'h', 'k', 'r' },
{ 'i', 'f', 'l', 'v' } };
String[] words = new String[] { "eat", "oath", "pea", "rain" };
List<String> list = findWords(board, words);
for (String s : list) {
System.out.println(s);
}
}
public static List<String> findWords(char[][] board, String[] words) {
TreeNode temp = BuildTree(words);
List<String> list = new ArrayList<>();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
findBackTracking(board, i, j, temp, list);
}
}
return list;
}
public static TreeNode BuildTree(String[] words) {
TreeNode root = new TreeNode();
for (int i = 0; i < words.length; i++) {
TreeNode temp = root;
char[] a = words[i].toCharArray();
for (char c : a) {
if (temp.next[c - 'a'] == null) {
temp.next[c - 'a'] = new TreeNode();
}
temp = temp.next[c - 'a'];
}
temp.word = words[i];
}
return root;
}
public static void findBackTracking(char[][] board, int x, int y,
TreeNode root, List<String> list) {
char c = board[x][y];
if (c == '$' || root.next[c - 'a'] == null) {
return;
}
root = root.next[c - 'a'];
if (root.word != null) {
list.add(root.word);
root.word = null;
}
board[x][y] = '$';
if (x > 0)
findBackTracking(board, x - 1, y, root, list);
if (x < board.length - 1)
findBackTracking(board, x + 1, y, root, list);
if (y > 0)
findBackTracking(board, x, y - 1, root, list);
if (y < board[0].length - 1)
findBackTracking(board, x, y + 1, root, list);
board[x][y] = c;
}
}
class TreeNode {
String word;
TreeNode[] next = new TreeNode[26];
}