关键词
回溯 trie(前缀树)
题目描述
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
说明:
你可以假设所有输入都由小写字母 a-z 组成。
提示:你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。什么样的数据结构可以有效地执行这样的操作?散列表是否可行?为什么? 前缀树如何?如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
低端解法
遍历 board,尝试以每个位置的单词为开头,向四周递归遍历,匹配目标单词。
- 记录遍历过程中的 trie 树的结点状态
- 回溯后的函数变量状态重置
import java.util.*;
class Solution {
class TrieNode {
/** 26 English character */
public TrieNode[] childs = new TrieNode[26];
public boolean isEnd = false;
public char value;
}
class Trie {
TrieNode root;
// 用于单字符查找回溯的栈和变量
Stack<TrieNode> stack = new Stack<>();
TrieNode cNode;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
cNode = root;
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = root;
for(int i=0;i<word.length();i++) {
int chIndex = word.charAt(i)-'a';
if(node.childs[chIndex] == null) {
node.childs[chIndex] = new TrieNode();
node.childs[chIndex].value = word.charAt(i);
}
node = node.childs[chIndex];
if(i == word.length()-1) {
node.isEnd = true;
}
}
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if (word == null || word.length() < 1) {
return false;
}
int chIndex;
TrieNode node = root;
for(char ch:word.toCharArray()) {
chIndex = ch - 'a';
if (node.childs[chIndex] == null) {
return false;
}
node = node.childs[chIndex];
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if (prefix == null || prefix.length() < 1) {
return false;
}
int chIndex;
TrieNode node = root;
for(char ch:prefix.toCharArray()) {
chIndex = ch - 'a';
if(node.childs[chIndex] == null) {
return false;
}
node = node.childs[chIndex];
}
return true;
}
public boolean traceIn(char ch) {
int chIndex = ch - 'a';
if (cNode.childs[chIndex] == null) {
return false;
}
cNode = cNode.childs[chIndex];
stack.push(cNode);
return true;
}
public void traceOut() {
stack.pop();
if (stack.isEmpty()) {
cNode = root;
return;
}
cNode = stack.peek();
}
public boolean cNodeIsEnd() {
return cNode.isEnd;
}
}
int ROW_SIZE;
int COL_SIZE;
boolean[][] visited;
HashSet<String> wordSet;
Trie trie = new Trie();
public void dfs(int row, int col, char[][] board, Trie trie) {
if (row < 0 || row >= ROW_SIZE || col < 0 || col >= COL_SIZE || visited[row][col]) {
return;
}
visited[row][col] = true;
if (trie.traceIn(board[row][col])) {
if (trie.cNodeIsEnd()) {
StringBuffer sb = new StringBuffer();
trie.stack.forEach((node) -> sb.append(node.value));
String word = sb.toString();
wordSet.add(word);
}
dfs(row-1, col, board, trie);
dfs(row+1, col, board, trie);
dfs(row, col+1, board, trie);
dfs(row, col-1, board, trie);
trie.traceOut();
}
visited[row][col] = false;
return;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<String>();
wordSet = new HashSet<String>();
if (words == null || board == null || board.length < 1 || board[0].length < 1) {
return result;
}
visited = new boolean[board.length][board[0].length];
for (String word : words) {
trie.insert(word);
}
ROW_SIZE = board.length;
COL_SIZE = board[0].length;
for (int row=0;row<ROW_SIZE;row++) {
for(int col=0;col<COL_SIZE;col++) {
dfs(row, col, board, trie);
}
}
for(String str: wordSet) {
result.add(str);
}
return result;
}
// 测试用例
public static void main(String[] args) {
Solution s = new Solution();
char[][] board = {{'a','a','a','a'},{'a','a','a','a'},{'a','a','a','a'},{'a','a','a','a'}};
String[] words = {"aaaaaaaaaaaa"};
s.findWords(board, words).forEach((str) -> System.out.println(str));
}
}

这篇博客介绍了LeetCode 212题——单词搜索II的解决方案,主要聚焦于Java实现。文章首先给出了问题的描述,接着详细阐述了一个基础的解法,即从二维网格的每个位置开始,利用回溯算法搜索并匹配字典中的单词,同时探讨了优化回溯算法的必要性和前缀树在解决此类问题中的应用。


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



