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 ...
随机推荐
- iframe和frameset的使用
iframe是:inner frame的缩写, 必须指明src属性,不能直接在里面写内容, 否则不会显示. 可以载入html, *.图片文件, txt文件等等. html的属性中,表示长度高度的尺寸属 ...
- [译]bare repository
git init --bare 使用--bare创建的repository没有工作目录, 在这个repository中不能修改文件和commit. 中心repository必须是bare reposi ...
- ASP 编码转换(乱码问题解决)
ASP 编码转换(乱码问题解决) 输出前先调用Conversion函数进行编码转换,可以解决乱码问题. 注,“&参数&”为ASP的连接符,这里面很多是直接调用的数据库表字段,实际使用请 ...
- Todd's Matlab讲义第6讲:割线法
割线法 割线法求解方程\(f(x)=0\)的根需要两个接近真实根\(x^\*\)的初值\(x_0\)和\(x_1\),于是得到函数\(f(x)\)上两个点\((x_0,y_0=f(x_0))\)和\( ...
- C#2.0 特性
泛型 迭代器 分布类 可空类型 匿名方法 命名空间别名限定符 静态类 外部程序程序集别名 属性访问器可访问性 委托中的协变和逆变 如何声明.实例化.使用委托 固定大小的缓冲区 友元程序集 内联警告控制 ...
- 如何利用cookie来保存用户登录账号
众所周知,cookie在网页编写中不接或缺,今天就谈谈如何利用cookie技术来保存用户登录账号 1.首先是否保存用户登录账号当然是用户自行决定,所以我们需要在用户登录界面设置一个复选框,以此取得用户 ...
- 推荐系统(协同过滤,slope one)
1.推荐系统中的算法: 协同过滤: 基于用户 user-cf 基于内容 item –cf slop one 关联规则 (Apriori 算法,啤酒与尿布) 2.slope one 算法 slope o ...
- 大数据之pig 命令
1.pig与hive的区别 pig和hive比较类似的,都是类sql的语言,底层都是依赖于hadoop 走的mapreduce任务. pig和hive的区别就是,想要实现一个业务逻辑的话, ...
- 循环执行n次的代码
var audio = document.createElement("audio"); var index = 0; audio.src = "piano/3C ...
- Redis学习笔记之ABC
Redis学习笔记之ABC Redis命令速查 官方帮助文档 中文版本1 中文版本2(反应速度比较慢) 基本操作 字符串操作 set key value get key 哈希 HMSET user:1 ...