Word Search II
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 the 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:
Input: words =["oath","pea","eat","rain"]
and board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] Output:["eat","oath"]
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
这题是在Word Search 基础上拓展而来的。很明显我们需要用到DFS来进行搜索。对于这种找某个string是否存在,Trie是个很有力的工具(因为查找检索快捷),所以这题采用了Trie+DFS的方法进行求解。
这里利用w.toCharArray()代替w.charAt(i) 以及在Tire树里面添加一个String变量来便于后期结果获取(这样就可以避免StringBuilder使用上的繁琐)。
class Solution {
class TireNode{
public TireNode[] children;
public String word;
public TireNode(){
children = new TireNode[26];
word = null;
}
}
public TireNode tireBuilder(String[] words){
TireNode root = new TireNode();
for(String w : words){
TireNode input = root;
for(char cur : w.toCharArray()){
int index = cur - 'a';
if(input.children[index] == null){
input.children[index] = new TireNode();
}
input = input.children[index];
}
input.word = w;
}
return root;
}
public void dfs(char[][] board, int i, int j, TireNode start, List<String> result){
if(i<0 || i== board.length
|| j<0 || j==board[0].length){
return;
}
char cur = board[i][j];
// Stop searching when the char has been visited or the word has been found
if(cur == '!' || start.children[cur-'a']==null){
return;
}
start = start.children[cur-'a'];
if(start.word!=null){
result.add(start.word);
start.word = null;
}
board[i][j] = '!';
dfs(board, i+1, j, start, result);
dfs(board, i-1, j, start, result);
dfs(board, i, j+1, start, result);
dfs(board, i, j-1, start, result);
board[i][j] = cur;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<>();
TireNode root = this.tireBuilder(words);
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
dfs(board, i, j, root, result);
}
}
return result;
}
}