https://leetcode.com/problems/word-search-ii/description/
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
.
SOLUTION 1:
思路是,先以words 建立一个Trie树,然后在这个Trie里搜索Boards里所有的字母,跟word search 1一样的搜索,找到一个word加到list里。
思路来自:https://discuss.leetcode.com/topic/33246/java-15ms-easiest-solution-100-00
1 class Solution { 2 class TrieNode { 3 TrieNode[] next = new TrieNode[26]; 4 String word; 5 } 6 7 public List<String> findWords(char[][] board, String[] words) { 8 if (board == null || board.length == 0 || board[0].length == 0) { 9 return null; 10 } 11 12 List<String> list = new ArrayList<String>(); 13 TrieNode root = buildTrie(words); 14 15 for (int i = 0; i < board.length; i++) { 16 for (int j = 0; j < board[0].length; j++) { 17 dfs(board, i, j, root, list); 18 } 19 } 20 21 return list; 22 } 23 24 public void dfs(char[][] board, int i, int j, TrieNode node, List<String> list) { 25 if (i < 0 || j < 0 || i >= board.length || j >= board[0].length) { 26 return; 27 } 28 29 char c = board[i][j]; 30 int n = c - 'a'; 31 if (c == '#' || node.next[n] == null) { 32 return; 33 } 34 35 node = node.next[n]; 36 board[i][j] = '#'; 37 if (node.word != null) { 38 list.add(node.word); 39 node.word = null; // One time search. 40 } 41 42 dfs(board, i + 1, j, node, list); 43 dfs(board, i - 1, j, node, list); 44 dfs(board, i, j + 1, node, list); 45 dfs(board, i, j - 1, node, list); 46 47 board[i][j] = c; 48 } 49 50 public TrieNode buildTrie(String[] words) { 51 TrieNode root = new TrieNode(); 52 53 for (String w: words) { 54 TrieNode node = root; 55 for (char c: w.toCharArray()) { 56 int n = c - 'a'; 57 if (node.next[n] == null) { 58 node.next[n] = new TrieNode(); 59 } 60 61 node = node.next[n]; 62 } 63 64 node.word = w; 65 } 66 67 return root; 68 } 69 }