• Word Search II

Word Search II

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. ['o','a','a','n'],
3. ['e','t','a','e'],
4. ['i','h','k','r'],
5. ['i','f','l','v']
6. ]

Return ["eat","oath"].
Note:
You may assume that all inputs are consist of lowercase letters a-z.
Hint:
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words’ prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Solution:
1. public class Solution {
2. int[] dx = {-1, 1, 0, 0};
3. int[] dy = {0, 0, -1, 1};
4. 5. public List findWords(char[][] board, String[] words) {
6. List res = new ArrayList();
7. 8. int n = board.length;
9. int m = board[0].length;
10. 11. boolean[][] used = new boolean[n][m];
12. 13. // use a hashset to avoid duplicates
14. Set set = new HashSet();
15. 16. // use a trie tree to avoid unnecessary search
17. Trie trie = new Trie();
18. for (String word : words)
19. trie.insert(word);
20. 21. // perform dfs from each position
22. for (int i = 0; i < n; i++)
23. for (int j = 0; j < m; j++)
24. search(board, n, m, i, j, "", used, trie, set, res);
25. 26. return res;
27. }
28. 29. void search(char[][] board, int n, int m, int i, int j, String word, boolean[][] used, Trie trie, Set set, List res) {
30. if (i < 0 || i >= n || j < 0 || j >= m || used[i][j])
31. return;
32. 33. word += board[i][j];
34. 35. // not the word we are looking for
36. if (!trie.startsWith(word))
37. return;
38. 39. if (!set.contains(word) && trie.search(word)) {
40. // found the word
41. set.add(word);
42. res.add(word);
43. }
44. 45. used[i][j] = true;
46. 47. for (int d = 0; d < 4; d++)
48. // continue dfs
49. search(board, n, m, i + dx[d], j + dy[d], word, used, trie, set, res);
50. 51. // backtracking
52. used[i][j] = false;
53. }
54. 55. class TrieNode {
56. // Initialize your data structure here.
57. char c;
58. boolean isLeaf;
59. Map children = new HashMap();
60. 61. public TrieNode() {}
62. public TrieNode(char c) { this.c = c; }
63. }
64. 65. public class Trie {
66. private TrieNode root;
67. 68. public Trie() {
69. root = new TrieNode();
70. }
71. 72. // Inserts a word into the trie.
73. public void insert(String word) {
74. Map children = root.children;
75. 76. for (int i = 0; i < word.length(); i++) {
77. char c = word.charAt(i);
78. 79. if (!children.containsKey(c))
80. children.put(c, new TrieNode(c));
81. 82. TrieNode t = children.get(c);
83. 84. if (i == word.length() - 1)
85. t.isLeaf = true;
86. 87. children = t.children;
88. }
89. }
90. 91. // Returns if the word is in the trie.
92. public boolean search(String word) {
93. TrieNode t = searchLastNode(word);
94. 95. return t != null && t.isLeaf;
96. }
97. 98. // Returns if there is any word in the trie
99. // that starts with the given prefix.
100. public boolean startsWith(String prefix) {
101. return searchLastNode(prefix) != null;
102. }
103. 104. // Returns the last TrieNode of word
105. private TrieNode searchLastNode(String word) {
106. Map children = root.children;
107. 108. for (int i = 0; i < word.length(); i++) {
109. char c = word.charAt(i);
110. 111. if (!children.containsKey(c))
112. break;
113. 114. TrieNode t = children.get(c);
115. 116. if (i == word.length() - 1)
117. return t;
118. 119. children = t.children;
120. }
121. 122. return null;
123. }
124. }
125. }