标签:
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.add(word); 6 } 7 8 List<String> res = new ArrayList<String>(); 9 for (int i = 0; i < board.length; i++) { 10 for (int j = 0; j < board[0].length; j++) { 11 trie.reset(); 12 search(res, board, "", i, j, trie); 13 } 14 } 15 return res; 16 } 17 18 private void search(List<String> res, char[][] board, String s, int x, int y, Trie trie) { 19 if (x >= board.length || y >= board[0].length || x < 0 || y < 0) { 20 return; 21 } 22 char c = board[x][y]; 23 if (c == ‘0‘) { 24 return; 25 } 26 int searchRes = trie.search(c); 27 Node current = trie.getCurrent(); 28 s += c; 29 if (searchRes == 0) { 30 return; 31 } else if (searchRes == 1) { 32 current.flag = false; 33 res.add(s); 34 } 35 board[x][y] = ‘0‘; 36 search(res, board, s, x + 1, y, trie); 37 trie.reset(current); 38 search(res, board, s, x - 1, y, trie); 39 trie.reset(current); 40 search(res, board, s, x, y + 1, trie); 41 trie.reset(current); 42 search(res, board, s, x, y - 1, trie); 43 board[x][y] = c; 44 } 45 46 private static class Trie{ 47 Node root = new Node(); 48 Node current = root; 49 50 public void add(String s) { 51 Node n = root; 52 for (int i = 0; i < s.length(); i++) { 53 int index = s.charAt(i) - 97; 54 if (n.nodes[index] == null) { 55 n.nodes[index] = new Node(); 56 } 57 n = n.nodes[index]; 58 } 59 n.flag = true; 60 } 61 62 public int search(char c) { 63 int index = c - 97; 64 if (current.nodes[index] == null) { 65 return 0; 66 } 67 current = current.nodes[index]; 68 if (current.flag) { 69 return 1; 70 } else { 71 return 2; 72 } 73 } 74 75 public Node getCurrent() { 76 return current; 77 } 78 79 public void reset() { 80 current = root; 81 } 82 83 public void reset(Node c) { 84 current = c; 85 } 86 } 87 88 private static class Node{ 89 boolean flag; 90 Node[] nodes = new Node[26]; 91 } 92 }
标签:
原文地址:http://www.cnblogs.com/wnan42/p/4682941.html