class Solution {
public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
TrieNode root = buildTrie(words);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs (board, i, j, root, res);
}
}
return res;
} public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
char c = board[i][j];
if (c == '#' || p.next[c - 'a'] == null) return;
p = p.next[c - 'a'];
if (p.word != null) { // found one
res.add(p.word);
p.word = null; // de-duplicate
} board[i][j] = '#';
if (i > 0) dfs(board, i - 1, j ,p, res);
if (j > 0) dfs(board, i, j - 1, p, res);
if (i < board.length - 1) dfs(board, i + 1, j, p, res);
if (j < board[0].length - 1) dfs(board, i, j + 1, p, res);
board[i][j] = c;
} public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode p = root;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (p.next[i] == null) p.next[i] = new TrieNode();
p = p.next[i];
}
p.word = w;
}
return root;
} class TrieNode {
TrieNode[] next = new TrieNode[26];
String word;
}
}

参考:https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)

leetcode212的更多相关文章

  1. [Swift]LeetCode212. 单词搜索 II | Word Search II

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  2. LeetCode212. Word Search II

    https://leetcode.com/problems/word-search-ii/description/ Given a 2D board and a list of words from ...

随机推荐

  1. ALGO-18_蓝桥杯_算法训练_单词接龙(搜索)

    问题描述 单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合 ...

  2. PREV-5_蓝桥杯_错误票据

    问题描述 某涉密单位下发了某种票据,并要在年终全部收回. 每张票据有唯一的ID号.全年所有票据的ID号是连续的,但ID的开始数码是随机选定的. 因为工作人员疏忽,在录入ID号的时候发生了一处错误,造成 ...

  3. C/C++基础----动态内存

    why 管理较难,忘记释放会内存泄漏,提早释放可能非法引用,重复释放. 为了更容易,更安全的使用动态内存,提供智能指针,其默认初始化保存一个空指针. what shared_ptr允许多个指针指向同一 ...

  4. Hadoop概念学习系列之Hadoop、Spark学习路线(很值得推荐)(十八)

    不多说,直接上干货! 说在前面的话 此笔,对于仅对于Hadoop和Spark初中学者.高手请忽略! 1 Java基础: 视频方面:          推荐<毕向东JAVA基础视频教程>.学 ...

  5. csv文件操作

    1.python2中: import csv infos = [ ['peter','male'], ['marry','female'], ['johon','male'], ['rose','fe ...

  6. js读取iframe里的元素

    父层 <div id="SubStepNav" class="SubStepNav"> <iframe src="aaa.html& ...

  7. jQuery 事件的命名空间简单了解

    原文地址:http://www.jb51.net/article/43626.htm   用 jQuery 绑定和解绑事件监听器都是非常简单的,怎样精确地解绑其中一个监听器?我们需要了解一下事件的命名 ...

  8. selector的小箭头去除

    selector的小箭头去除 .not-arrow{ -webkit-appearance:none; -moz-appearance:none; appearance:none; /*去掉下拉箭头* ...

  9. 安装sublime txt3 并且设置为默认的text打开方式

    1.安装 安装可以参考 http://jingyan.baidu.com/article/fa4125acb8569b28ac7092ea.html 1.添加sublime text 3的仓库: su ...

  10. MVC 访问静态页面 View 下面放JS

    http://blog.csdn.net/qq_17255515/article/details/53293120