Word Search I & II
Word Search I
Given a 2D board and a word, find if the word exists in the grid.
The word can 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.
Example
Given board =
[
"ABCE",
"SFCS",
"ADEE"
]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == || board[].length == ) return false;
if (word.length() == ) return true; int rows = board.length, cols = board[].length;
boolean[][] visited = new boolean[rows][cols];
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (helper(board, i, j, word, , visited)) return true;
}
}
return false;
} public boolean helper(char[][] board, int i, int j, String word, int index, boolean[][] visited) {
if (index == word.length()) return true; if (i < || i >= board.length || j < || j >= board[].length) return false;
if (board[i][j] != word.charAt(index) || visited[i][j] == true) return false;
visited[i][j] = true;
int[][] dir = {{, }, {, -}, {, }, {-, }};
for (int row = ; row < dir.length; row++) {
int new_row = i + dir[row][];
int new_col = j + dir[row][];
if (helper(board, new_row, new_col, word, index + , visited)) {
return true;
}
}
visited[i][j] = false;
return false;
}
}
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 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"]
.
方法一:
把每个点作为起始点,然后朝四个方向遍历,从起始点到当前点组成的字符串如果在trie中能够找到,继续,否则,退出。
第二种方法:
把每个TrieNode放入递归方法中,如果当前字符和TrieNode的字符一致,我们再把TrieNode的每个子节点作为递归节点继续,否则退出。
public class Solution {
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String word : words) {
trie.insert(word);
}
Set<String> set = new HashSet<>();
int m = board.length, n = board[].length;
boolean[][] visited = new boolean[m][n]; for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
dfs(board, visited, i, j, trie.root.map.get(board[i][j]), new StringBuilder(), set);
}
}
return new ArrayList<String>(set);
} public void dfs(char[][] board, boolean[][] visited, int i, int j, TrieNode node, StringBuilder sb, Set<String> set) {
int m = board.length, n = board[].length;
if (node == null || i < || j < || i >= m || j >= n || visited[i][j]) return;
if (board[i][j] != node.ch) return; sb.append(node.ch);
if (node.isEnd) {
set.add(sb.toString());
} visited[i][j] = true;
for (TrieNode curr : node.map.values()) {
dfs(board, visited, i - , j, curr, sb, set);
dfs(board, visited, i + , j, curr, sb, set);
dfs(board, visited, i, j - , curr, sb, set);
dfs(board, visited, i, j + , curr, sb, set);
}
visited[i][j] = false;
sb.deleteCharAt(sb.length() - );
}
} class TrieNode {
char ch;
boolean isEnd;
Map<Character, TrieNode> map; public TrieNode(char ch) {
this.ch = ch;
map = new HashMap<Character, TrieNode>();
} public TrieNode getChildNode(char ch) {
return map.get(ch);
}
} // Trie
class Trie {
public TrieNode root = new TrieNode(' '); public void insert(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
TrieNode child = current.getChildNode(c);
if (child == null) {
child = new TrieNode(c);
current.map.put(c, child);
}
current = child;
}
current.isEnd = true;
}
}
参考请注明出处:cnblogs.com/beiyeqingteng/
Word Search I & II的更多相关文章
- LeetCode解题报告—— Word Search & Subsets II & Decode Ways
1. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be con ...
- Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)
Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...
- leetcode 79. Word Search 、212. Word Search II
https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...
- 【leetcode】212. Word Search II
Given an m x n board of characters and a list of strings words, return all words on the board. Each ...
- [LeetCode] Word Search II 词语搜索之二
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- Java for LeetCode 212 Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- 212. Word Search II
题目: Given a 2D board and a list of words from the dictionary, find all words in the board. Each word ...
- Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- [LeetCode] 212. Word Search II 词语搜索之二
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
随机推荐
- MVC缓存OutPutCache学习笔记 (二) 缓存及时化VaryByCustom
<MVC缓存OutPutCache学习笔记 (一) 参数配置> 本篇来介绍如何使用 VaryByCustom参数来实现缓存的及时化.. 根据数据改变来及时使客户端缓存过期并更新.. 首先更 ...
- array_flip() array_merge() array+array的使用总结
array_flip(array); //传递一个数组参数,对该数组的键.值进行翻转 例如: $a = array( 'a', 'b', 'c' ); print_r(array_flip($a)); ...
- Ajax 局部刷新
方式一:function hits1(troops) { var troops = troops; var ajax=Ajax(); var url = 'xxx.php'; ...
- 为IIS Express添加MIME映射
VS2013自带IIS Express,无法发布JSON文件,需添加MIME映射. 没有图形界面,只能命令行. 进入C:\Program Files(x86)\IIS Express文件夹,输入:ap ...
- linux下文件结束符
linux下文件结束符,我试过了所有的linux,发现其文件的结束符都是以0a即LF结束的,这个是操作系统规定的,windows下是\r\n符结束,希望可以帮助大家. -------------转:来 ...
- 后缀.jar的是什么文件?
解压kafka 打开后是一堆.jar结尾的文件,那么后缀.jar的是什么文件? JAR 文件就是 Java Archive File,顾名思意,它的应用是与 Java 息息相关的,是 Java 的一种 ...
- nanosleep() -- 更精确的延迟 -----一个使用用例
[常规] nanosleep() -- 更精确的延迟 [复制链接] beyes 4220 主题 5152 帖子 3万 积分 GROAD 曲径通幽,安觅芳踪. 积分 30607 发消息 电梯直达 ...
- 推荐 10 个超棒的 CSS3 代码生成工具
新的在线工具和 WebApp 帮助开发者快速地创建网站而不用写代码.前端开发已经在框架和代码库方面有了很大的进展. 但是许多开发者已经忘记了代码生成器在构建网站时的价值.下面的资源是完全免费的 Web ...
- [译]Mongoose指南 - Plugin
Schema支持插件, 这样你就可以扩展一些额功能了 下面的例子是当document save的时候自定更新最后修改日期的出插件 // lastMod.js module.exports = expo ...
- Codeforces Round #270 1003
Codeforces Round #270 1003 C. Design Tutorial: Make It Nondeterministic time limit per test 2 second ...