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. mysql中Can't connect to MySQL server on 'localhost' (10061)

    Can't connect to MySQL server on 'localhost' (10061) 第一问题有两个解决方案: 1)没有启动sql服务,以下是具体步骤: 右键-计算机-管理-服务和 ...

  2. OC-成员变量的作用域

    #import <Foundation/Foundation.h> @interface Person : NSObject { int _no; @public // 在任何地方都能直接 ...

  3. OC-类方法

    类方法 1. 基本概念 直接可以用类名来执行的方法(类本身会在内存中占据存储空间,里面有类\对象方法列表) 2. 类方法和对象方法对比 1)  对象方法 以减号-开头 只能让对象调用,没有对象,这个方 ...

  4. MongoDB学习笔记(索引)(转)

    一.索引基础:    MongoDB的索引几乎与传统的关系型数据库一模一样,这其中也包括一些基本的优化技巧.下面是创建索引的命令:    > db.test.ensureIndex({" ...

  5. Android Studio-开启Preview视图

    Preview视图会在切换"Design"和"Text"视图的时候自动显示,可在右侧工具栏开启: 今天无意中关闭了,找了半天,原来可以在这个地方再次开启:

  6. css使 同一行内的 文字和图片 垂直居中对齐?

    设置父容器, 使 父容器 div 下的所有元素 都 垂直对齐: father-container *{ vertical-align:middle 找回密码

  7. nginx同一iP多域名配置方法

    文章转自:http://blog.itblood.com/nginx-same-ip-multi-domain-configuration.html 下面的是我本机的配置: server { list ...

  8. CF460D Little Victor and Set (找规律)

    D - Little Victor and Set Codeforces Round #262 (Div. 2) D D. Little Victor and Set time limit per t ...

  9. 编译CDH Spark源代码

    如何编译CDH Spark源代码 经过漫长的编译过程(我编译了2个半小时),最终成功了,在assembly/target/scala-2.10目录下面有spark-assembly-1.0.0-cdh ...

  10. mysql 修改表结构

    alter table 表名 modify column 字段名 varchar(数量); 将varchar(50)改为255 alter table 表名 modify column 字段名 var ...