Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

- 使用Trie树在DFS的过程中记录到达的结点
- 当搜索到一个单词后不可能再次搜索这个单词
- 因此将这个单词从trie树中移除
- 如果该结点没有子节点,则将该结点从trie树中移除
- 递归的向上删除结点,直到根结点
- 这里的删除操作仅将map的值域置为null
class Solution {
class Trie{
String word;
Map<Character,Trie> child = new HashMap<>();
boolean isword = false;
//向trie中插入单词
public Trie(String word)
{
this.word = word;
}
public void Insert(String word)
{
Trie cur = this;
for(int i = 0;i<word.length();i++)
{
if(!cur.child.containsKey(word.charAt(i))) //如果孩子结点不包含该单词
{
Trie temp = new Trie(cur.word + word.charAt(i));
child.put(word.charAt(i),temp);
}
cur = cur.child.get(word.charAt(i));
}
cur.isword = true;
}
}
public boolean DFS(Set<String> ans,int[][] choice,char[][] board,Trie now,int i,int j)
{
if(now.isword)
{
ans.add(now.word);
now.isword = false;
}
char ch = board[i][j];
board[i][j] = '0';
for (int[] ints : choice) {
if (i + ints[0] >= 0 && i + ints[0] < board.length && j + ints[1] >= 0 && j + ints[1] < board[0].length && board[i + ints[0]][j + ints[1]] != '0' && now.child.get(board[i + ints[0]][j + ints[1]]) != null)
if(DFS(ans, choice, board, now.child.get(board[i + ints[0]][j + ints[1]]), i + ints[0], j + ints[1]))
{
//下层该结点返回自己已经没有孩子了
now.child.remove(board[i + ints[0]][j + ints[1]]);
}
}
board[i][j] = ch;
return !now.isword && now.child.isEmpty();
}
public List<String> findWords(char[][] board, String[] words) {
//四种选择
int[][] choices = {{-1,0},{1,0},{0,-1},{0,1}};
Trie root = new Trie("");
for(String i:words)
root.Insert(i);
Set<String> ans = new HashSet<>();
for(int i = 0;i<board.length;i++)
for(int j = 0;j<board[0].length;j++)
{
if(root.child.get(board[i][j])!=null)
{
DFS(ans,choices,board,root.child.get(board[i][j]),i,j);
}
}
return new ArrayList<>(ans);
}
}
这篇博客介绍了如何利用Trie树数据结构结合深度优先搜索(DFS)策略,在给定的二维字符板上查找并返回所有存在的单词。在DFS过程中,删除已搜索过的单词以避免重复,并在递归过程中优化Trie树,提高搜索效率。这种方法适用于解决字符网格上的单词查找挑战。
792

被折叠的 条评论
为什么被折叠?



