当前位置:   article > 正文

Java | Leetcode Java题解之第212题单词搜索II

Java | Leetcode Java题解之第212题单词搜索II

题目:

题解:

  1. class Solution {
  2. int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
  3. public List<String> findWords(char[][] board, String[] words) {
  4. Trie trie = new Trie();
  5. for (String word : words) {
  6. trie.insert(word);
  7. }
  8. Set<String> ans = new HashSet<String>();
  9. for (int i = 0; i < board.length; ++i) {
  10. for (int j = 0; j < board[0].length; ++j) {
  11. dfs(board, trie, i, j, ans);
  12. }
  13. }
  14. return new ArrayList<String>(ans);
  15. }
  16. public void dfs(char[][] board, Trie now, int i1, int j1, Set<String> ans) {
  17. if (!now.children.containsKey(board[i1][j1])) {
  18. return;
  19. }
  20. char ch = board[i1][j1];
  21. Trie nxt = now.children.get(ch);
  22. if (!"".equals(nxt.word)) {
  23. ans.add(nxt.word);
  24. nxt.word = "";
  25. }
  26. if (!nxt.children.isEmpty()) {
  27. board[i1][j1] = '#';
  28. for (int[] dir : dirs) {
  29. int i2 = i1 + dir[0], j2 = j1 + dir[1];
  30. if (i2 >= 0 && i2 < board.length && j2 >= 0 && j2 < board[0].length) {
  31. dfs(board, nxt, i2, j2, ans);
  32. }
  33. }
  34. board[i1][j1] = ch;
  35. }
  36. if (nxt.children.isEmpty()) {
  37. now.children.remove(ch);
  38. }
  39. }
  40. }
  41. class Trie {
  42. String word;
  43. Map<Character, Trie> children;
  44. boolean isWord;
  45. public Trie() {
  46. this.word = "";
  47. this.children = new HashMap<Character, Trie>();
  48. }
  49. public void insert(String word) {
  50. Trie cur = this;
  51. for (int i = 0; i < word.length(); ++i) {
  52. char c = word.charAt(i);
  53. if (!cur.children.containsKey(c)) {
  54. cur.children.put(c, new Trie());
  55. }
  56. cur = cur.children.get(c);
  57. }
  58. cur.word = word;
  59. }
  60. }
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号