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.

分析:
在board这个数组里,每个字符都可能是起始字符,所以我们得遍历所有字符,以它作为其实字符,如果该字符与target字符串第一个字符相同,然后我们在board数组里各个方向进行搜索。直到target最后一个字符被找到为止。
 
 1 public class Solution {
 2     public boolean exist(char[][] board, String word) {
 3         if (board == null || board.length == 0 || board[0].length == 0) return false;
 4         if (word.length() == 0) return true;
 5 
 6         int rows = board.length, cols = board[0].length;
 7         boolean[][] visited = new boolean[rows][cols];
 8         boolean[] result = new boolean[1];
 9         for (int i = 0; i < rows; i++) {
10             for (int j = 0; j < cols; j++) {
11                 helper(board, i, j, word, 0, visited, result);
12             }
13         }
14         return result[0];
15     }
16 
17     public void helper(char[][] board, int i, int j, String word, int index, boolean[][] visited, boolean[] result) {
18         if (index == word.length()) {
19             result[0] = true;
20         }
21         
22         if (result[0] || i < 0 || i >= board.length || j < 0 || j >= board[0].length) return;
23         if (board[i][j] != word.charAt(index) || visited[i][j] == true) return;
24         
25         visited[i][j] = true;
26         helper(board, i + 1, j, word, index + 1, visited, result);
27         helper(board, i - 1, j, word, index + 1, visited, result);
28         helper(board, i, j + 1, word, index + 1, visited, result);
29         helper(board, i, j - 1, word, index + 1, visited, result);
30         visited[i][j] = false;
31     }
32 }

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的每个子节点作为递归节点继续,否则退出。

 1 public class Solution {
 2     public List<String> findWords(char[][] board, String[] words) {
 3         Trie trie = new Trie();
 4         for (String word : words) {
 5             trie.insert(word);
 6         }
 7         Set<String> set = new HashSet<>();
 8         int m = board.length, n = board[0].length;
 9         boolean[][] visited = new boolean[m][n];
10 
11         for (int i = 0; i < m; i++) {
12             for (int j = 0; j < n; j++) {
13                 dfs(board, visited, i, j, trie.root.map.get(board[i][j]), new StringBuilder(), set);
14             }
15         }
16         return new ArrayList<String>(set);
17     }
18 
19     public void dfs(char[][] board, boolean[][] visited, int i, int j, TrieNode node, StringBuilder sb, Set<String> set) {
20         int m = board.length, n = board[0].length;
21         if (node == null || i < 0 || j < 0 || i >= m || j >= n || visited[i][j]) return;
22         if (board[i][j] != node.ch) return;
23 
24         sb.append(node.ch);
25         if (node.isEnd) {
26             set.add(sb.toString());
27         }
28         
29         visited[i][j] = true;
30         for (TrieNode curr : node.map.values()) {
31             dfs(board, visited, i - 1, j, curr, sb, set);
32             dfs(board, visited, i + 1, j, curr, sb, set);
33             dfs(board, visited, i, j - 1, curr, sb, set);
34             dfs(board, visited, i, j + 1, curr, sb, set);
35         }
36         visited[i][j] = false;
37         sb.deleteCharAt(sb.length() - 1);
38     }
39 }
40 
41 class TrieNode {
42     char ch;
43     boolean isEnd;
44     Map<Character, TrieNode> map;
45 
46     public TrieNode(char ch) {
47         this.ch = ch;
48         map = new HashMap<Character, TrieNode>();
49     }
50 
51     public TrieNode getChildNode(char ch) {
52         return map.get(ch);
53     }
54 }
55 
56 // Trie
57 class Trie {
58     public TrieNode root = new TrieNode(' ');
59 
60     public void insert(String word) {
61         TrieNode current = root;
62         for (char c : word.toCharArray()) {
63             TrieNode child = current.getChildNode(c);
64             if (child == null) {
65                 child = new TrieNode(c);
66                 current.map.put(c, child);
67             }
68             current = child;
69         }
70         current.isEnd = true;
71     }
72 }

参考请注明出处:cnblogs.com/beiyeqingteng/

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5625530.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值