79. 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最后一个字符被找到为止。
时间复杂度为O(m*n*4^s). m is row count, n is col count, s is string length.
 
 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         for (int i = 0; i < rows; i++) {
 9             for (int j = 0; j < cols; j++) {
10                 if (helper(board, i, j, word, 0, visited)) return true;
11             }
12         }
13         return false;
14     }
15 
16     public boolean helper(char[][] board, int i, int j, String word, int index, boolean[][] visited) {
17         if (board[i][j] != word.charAt(index)) return false;
18         if (index == word.length() - 1) return true;
19         visited[i][j] = true;
20         int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
21         for (int row = 0; row < dir.length; row++) {
22             int new_row = i + dir[row][0];
23             int new_col = j + dir[row][1];
24             if (new_row >= 0 && new_row < board.length && new_col >= 0 && new_col < board[0].length
25                     && !visited[new_row][new_col]) {
26                 if (helper(board, new_row, new_col, word, index + 1, visited)) {
27                     return true;
28                 }
29             }
30         }
31         visited[i][j] = false;
32         return false;
33     }
34 }

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/

 
posted @ 2016-06-29 03:13  北叶青藤  阅读(307)  评论(0编辑  收藏  举报