212.word-search-ii.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. root.cnt = -1;
  15. for (String word : words) root.insert(word);
  16. for (int y = 0; y < n; y++) {
  17. for (int x = 0; x < m; x++) {
  18. StringBuilder sb = new StringBuilder();
  19. backtrack(y, x, root, sb, res);
  20. }
  21. }
  22. return res;
  23. }
  24. private void backtrack(int y, int x, TrieNode curr, StringBuilder sb, LinkedList<String> res) {
  25. if (curr == null || curr.cnt == 0) return;
  26. if (curr.isKey) {
  27. res.add(sb.toString());
  28. root.remove(sb.toString());
  29. }
  30. char c;
  31. if (y < 0 || n <= y || x < 0 || m <= x || (c = board[y][x]) == '#') return;
  32. sb.append(c);
  33. board[y][x] = '#';
  34. curr = curr.next[(int) c - 'a'];
  35. for (int i = 0; i < 4; i++) {
  36. int ny = y + dy[i], nx = x + dx[i];
  37. backtrack(ny, nx, curr, sb, res);
  38. }
  39. sb.deleteCharAt(sb.length() - 1);
  40. board[y][x] = c;
  41. }
  42. class TrieNode {
  43. int cnt;
  44. boolean isKey;
  45. TrieNode[] next = new TrieNode[26];
  46. void insert(String str) {
  47. TrieNode curr = this;
  48. for (char c : str.toCharArray()) {
  49. int i = (int) c - 'a';
  50. if (curr.next[i] == null) curr.next[i] = new TrieNode();
  51. curr = curr.next[i];
  52. curr.cnt++;
  53. }
  54. curr.isKey = true;
  55. }
  56. void remove(String str) {
  57. TrieNode curr = this;
  58. for (char c : str.toCharArray()) {
  59. int i = (int) c - 'a';
  60. curr = curr.next[i];
  61. curr.cnt--;
  62. }
  63. curr.isKey = false;
  64. }
  65. }
  66. }