|
@@ -16,33 +16,32 @@ class Solution {
|
|
|
root = new TrieNode();
|
|
|
root.cnt = -1;
|
|
|
for (String word : words) root.insert(word);
|
|
|
- boolean[][] used = new boolean[n][m];
|
|
|
for (int y = 0; y < n; y++) {
|
|
|
for (int x = 0; x < m; x++) {
|
|
|
StringBuilder sb = new StringBuilder();
|
|
|
- backtrack(y, x, root, sb, used, res);
|
|
|
+ backtrack(y, x, root, sb, res);
|
|
|
}
|
|
|
}
|
|
|
return res;
|
|
|
}
|
|
|
|
|
|
- private void backtrack(int y, int x, TrieNode curr, StringBuilder sb, boolean[][] used, LinkedList<String> res) {
|
|
|
+ private void backtrack(int y, int x, TrieNode curr, StringBuilder sb, LinkedList<String> res) {
|
|
|
if (curr == null || curr.cnt == 0) return;
|
|
|
if (curr.isKey) {
|
|
|
res.add(sb.toString());
|
|
|
root.remove(sb.toString());
|
|
|
}
|
|
|
- if (y < 0 || n <= y || x < 0 || m <= x || used[y][x]) return;
|
|
|
- char c = board[y][x];
|
|
|
+ char c;
|
|
|
+ if (y < 0 || n <= y || x < 0 || m <= x || (c = board[y][x]) == '#') return;
|
|
|
sb.append(c);
|
|
|
- used[y][x] = true;
|
|
|
+ board[y][x] = '#';
|
|
|
curr = curr.next[(int) c - 'a'];
|
|
|
for (int i = 0; i < 4; i++) {
|
|
|
int ny = y + dy[i], nx = x + dx[i];
|
|
|
- backtrack(ny, nx, curr, sb, used, res);
|
|
|
+ backtrack(ny, nx, curr, sb, res);
|
|
|
}
|
|
|
sb.deleteCharAt(sb.length() - 1);
|
|
|
- used[y][x] = false;
|
|
|
+ board[y][x] = c;
|
|
|
}
|
|
|
|
|
|
class TrieNode {
|