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.

分析:
在board这个数组里,每个字符都可能是起始字符,所以我们得遍历所有字符,以它作为其实字符,如果该字符与target字符串第一个字符相同,然后我们在board数组里各个方向进行搜索。直到target最后一个字符被找到为止。
时间复杂度为O(m*n*4^s). m is row count, n is col count, s is string length.
 
 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的更多相关文章

  1. 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 ...

  2. Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)

    Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...

  3. leetcode 79. Word Search 、212. Word Search II

    https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...

  4. 【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 ...

  5. [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 ...

  6. 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 ...

  7. 212. Word Search II

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

  8. Word Search II

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

  9. [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 ...

随机推荐

  1. .net mvc web api 返回 json 内容,过滤值为null的属性

    原文:http://blog.csdn.net/xxj_jing/article/details/49508557 版权声明:本文为博主原创文章,未经博主允许不得转载. .net mvc web ap ...

  2. mysql 插入/更新数据

    mysql 插入/更新数据 INSERT 语句 1.一次性列出全部字段的值,例如: INSERT INTO student VALUES('Chenqi','M', 29); INSERT INTO ...

  3. EF: Raw SQL Queries

    Raw SQL Queries Entity Framework allows you to query using LINQ with your entity classes. However, t ...

  4. .NET对象判等归纳与总结

    1.引言 最近在看<CLR via C#>看到对象判等的那一节,觉得这也是.NET基础知识中比较重要的部分就写一篇博文来简单的总结归纳一下. 2..NET下的对象判等 在.NET中关于对象 ...

  5. PhpStorm 快捷键

    不容易记住的: Ctrl + Shift + F  查找文本,在项目目录或指定的目录 Ctrl + Shift + R  查找文本并替换,在项目目录或指定的目录 Ctrl + E    打开最近关闭的 ...

  6. 多线程 GET

    iOS中多线程的实现 方案 简介 语言 线程生命周期 使用频率 pthread 一套通用的多线程API 适用于 Unix / Linux / Windows 等系统 跨平台\可移植 使用难度大 C 程 ...

  7. 分词工具ICTCLAS5.0使用心得

    接触自然语言处理有一年多了,最基本的一些自然是分词,词性标注,命名实体识别之类的知识,有些应用知道原理是一回事,自己动手做起来又是另外一回事了.最近又开始重操旧业:分词.分词最著名的自然就是中科院的分 ...

  8. objective-c与c++的差异

    oc的编译指令为 clang -fobjc-arc -framework Foundation test.m -o test oc中,1表示YES,0表示NO.并不是非0值都是YES,这是因为BOOL ...

  9. 让我们一起学Node.js-文章列表

    新浪的博客最近不给力,只好在博客园落个窝.至此之后,技术随笔会在博客园以及新浪的博客上同时更新,如果新浪给力的话~~~ 如果你想看先前新浪博客上分享的技术,请点击此处 忘尘子新浪博客! 我是拜读了朴灵 ...

  10. SQL 分组后获取其中一个字段最大值的整条记录

    --有id,name,createDate的一张表testTable--根据name分组,获取每组中createDate最大的那条记录(整条)查询出来------------------------- ...