HARD
Java:搜索全部可能
class Solution {
StringBuilder sb;
List<String> list;
Set<String> set;
private void dfs(int x, int y, int m, int n, char[][] board){
if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] == '.') {
return;
}
if (sb.length() > 10) { // 剪枝,不然超时
return;
}
char ch = board[x][y];
sb.append(ch); // 放在set判断之前
if (set.contains(sb.toString())) {
list.add(sb.toString());
set.remove(sb.toString()); // oaa oa oa 题意没告诉不能重复放入ans
}
board[x][y] = '.';
dfs(x + 1, y, m, n, board);
dfs(x - 1, y, m, n, board);
dfs(x, y + 1, m, n, board);
dfs(x, y - 1, m, n, board);
board[x][y] = ch;
sb.deleteCharAt(sb.length() - 1);
}
public List<String> findWords(char[][] board, String[] words) {
sb = new StringBuilder();
list = new ArrayList<>();
set = new HashSet<>();
for (String str : words) {
set.add(str);
}
int m = board.length, n = board[0].length;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
dfs(i, j, m, n, board); // 遍历所有的字符串起点!
}
}
return list;
}
}