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 ...
随机推荐
- yii2 登录、退出、自动登录
自动登录的原理很简单.主要就是利用cookie来实现的在第一次登录的时候,如果登录成功并且选中了下次自动登录,那么就会把用户的认证信息保存到cookie中,cookie的有效期为1年或者几个月. 在下 ...
- C#实现Excel模板导出和从Excel导入数据
午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.Office.Interop.Excel 3.封装的Exc ...
- js字符串转成数字的三种方法
js读取的html代码中获得的值 ,统统是以字符串的形式呈现的,为了方便我们后面对数据的操作,有时候我们有必要进行转换一下. 方法主要有三种 转换函数.强制类型转换.利用js变量弱类型转换. 1. 转 ...
- [EWS]在exchange中的标识符
摘要 最近在用ews的方式开发邮箱服务,包括写邮件,查看某封邮件的详情,回复,全部回复及转发功能.在获取收件箱的时候,关于唯一标识符的问题.也有点困惑,在每个邮件item中,存在一个changeKey ...
- xml基础总结
可扩展的标记语言(eXtensible Markup Language) 优点:容易读懂:格式标准任何语言都内置了XML分析引擎,不用单独进行文件分析引擎的编写. 用普通二进制传输数据的缺点,解析方式 ...
- \r,\n,\r\n的区别
http://www.studyofnet.com/news/285.html \n是换行,英文是New line,表示使光标到行首\r是回车,英文是Carriage return,表示使光标下移一格 ...
- jQuery 学习之路(1):引子
一.主流 javascript 库 除 jQuery 外,还有 Prototype.Dojo.YUI.ExtJS.MooTools ,其中 Prototype 较老,结构设计较为松散,ExtJS 界面 ...
- thinkPHP3.2.3集成swoole扩展
swoole.php #!/bin/env php <?php /** * 默认时区定义 */ date_default_timezone_set('Asia/Shanghai'); /** * ...
- angular $resource模块
目录(?)[-] 安装 应用resource 扩展resource 上一篇中讲到使用$http同服务器进行通信,但是功能上比较简单,angularjs还提供了另外一个可选的服务$resource, ...
- linux系统安装yum环境
http://blog.sina.com.cn/s/blog_63d8dad80101cn2s.html 1.卸载rhel的默认安装的yum包 查看yum包 rpm -qa|grep yum 卸载之 ...