212. 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"].

 

Note:
You may assume that all inputs are consist of lowercase letters a-z.

 

Similar: 79. Word Search

 

 1 public class Solution {
 2     class Trie {
 3         Trie[] childs;
 4         String word; // can not be boolean
 5         public Trie() {
 6             childs = new Trie[26];
 7         }
 8     }
 9     private void buildTrie(String word, Trie node) {
10         for (char c : word.toCharArray()) {
11             int i = c - 'a';
12             if (node.childs[i]  == null) node.childs[i] = new Trie();
13             node = node.childs[i];
14         }
15         
16         node.word = word;
17     }
18     
19     public List<String> findWords(char[][] board, String[] words) {
20         if (board.length == 0 || board[0].length == 0 || words.length == 0)
21             return new LinkedList<String>();
22             
23         LinkedList<String> ret = new LinkedList<String>();
24         
25         Trie root = new Trie();
26         for (String word : words) {
27             buildTrie(word, root);
28         }
29         
30         for (int i = 0; i < board.length; i++) {
31             for (int j = 0; j < board[0].length; j++) {
32                 dfs(board, root, i, j, ret);
33             }
34         }
35         return ret;
36     }
37     
38     private void dfs(char[][] board, Trie root, int r, int c, LinkedList<String> ret) {
39         char ch = board[r][c];
40         
41         if (ch == '#' || root.childs[ch - 'a'] == null) return;
42         
43         root = root.childs[ch - 'a'];
44         if (root.word != null)  {
45             ret.add(root.word);
46             root.word = null; // de-duplicate
47         }
48         
49         board[r][c] = '#';
50         
51         if (r > 0)  dfs(board, root, r - 1, c, ret);
52             
53         if (r < board.length - 1) dfs(board, root, r + 1, c, ret);
54             
55         if (c > 0) dfs(board, root, r, c - 1, ret);
56             
57         if (c < board[0].length - 1) dfs(board, root, r, c + 1, ret);
58         
59         board[r][c] = ch;
60         
61     }
62 }

 

posted @ 2016-05-11 12:13  Joyce-Lee  阅读(232)  评论(0编辑  收藏  举报