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 =
1 2 3 4 5 6 [ ['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.
Backtracking + Trie 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 public class Solution { public class TrieNode { TrieNode[] next; String word; public TrieNode () { next = new TrieNode[26 ]; } } public List<String> findWords (char [][] board, String[] words) { List<String> result = new LinkedList<>(); if (words == null || words.length == 0 ) { return result; } TrieNode root = buildTrie(words); for (int i = 0 ; i < board.length; i++) { for (int j = 0 ; j < board[0 ].length; j++) { dfs(board, i, j, result, root); } } return result; } public void dfs (char [][] board, int i, int j, List<String> result, TrieNode root) { char cur = board[i][j]; if (cur == '#' || root.next[cur - 'a' ] == null ) return ; root = root.next[cur - 'a' ]; if (root.word != null ) { result.add(root.word); root.word = null ; } board[i][j] = '#' ; if (i > 0 ) dfs(board, i - 1 , j, result, root); if (i < board.length - 1 ) dfs(board, i + 1 , j, result, root); if (j > 0 ) dfs(board, i, j - 1 , result, root); if (j < board[0 ].length - 1 ) dfs(board, i, j + 1 , result, root); board[i][j] = cur; } public TrieNode buildTrie (String[] words) { TrieNode root = new TrieNode(); for (String str : words) { TrieNode cur = root; for (char c : str.toCharArray()) { if (cur.next[c - 'a' ] == null ) { cur.next[c - 'a' ] = new TrieNode(); } cur = cur.next[c - 'a' ]; } cur.word = str; } return root; } }