212.word-search-ii.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import java.util.LinkedList;
  2. class Solution {
  3. private int[] dy = new int[]{0, 1, 0, -1};
  4. private int[] dx = new int[]{1, 0, -1, 0};
  5. private char[][] board;
  6. private int n;
  7. private int m;
  8. private TrieNode root;
  9. public List<String> findWords(char[][] board, String[] words) {
  10. LinkedList<String> res = new LinkedList<>();
  11. if ((n = board.length) == 0 || (m = board[0].length) == 0 || words.length == 0) return res;
  12. this.board = board;
  13. root = new TrieNode();
  14. for (String word : words) root.insert(word);
  15. for (int y = 0; y < n; y++)
  16. for (int x = 0; x < m; x++)
  17. backtracking(y, x, root, res);
  18. return res;
  19. }
  20. private void backtracking(int y, int x, TrieNode curr, LinkedList<String> res) {
  21. if (curr == null) return;
  22. if (curr.word != null) {
  23. res.add(curr.word);
  24. curr.word = null;
  25. }
  26. char c;
  27. if (y < 0 || n <= y || x < 0 || m <= x || (c = board[y][x]) == '#') return;
  28. board[y][x] = '#';
  29. curr = curr.next[c - 'a'];
  30. for (int i = 0; i < 4; i++) backtracking(y + dy[i], x + dx[i], curr, res);
  31. board[y][x] = c;
  32. }
  33. class TrieNode {
  34. String word;
  35. TrieNode[] next = new TrieNode[26];
  36. void insert(String str) {
  37. TrieNode curr = this;
  38. for (char c : str.toCharArray()) {
  39. int i = c - 'a';
  40. if (curr.next[i] == null) curr.next[i] = new TrieNode();
  41. curr = curr.next[i];
  42. }
  43. curr.word = str;
  44. }
  45. }
  46. }