想知道我的代码哪里出错了,请帮助我获得预期的输出。提前致谢。##Word 搜索 II## 来自 leetcode:
代码:
class Solution {
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<String>();
if (board.length <= 0 || words.length <= 0) {
return result;
}
for (int i = 0; i < words.length; i++) {
if (result.contains(words[i])) {
continue;
}
for (int j = 0; j < board.length; j++) {
for (int k = 0; k < board[0].length; k++) {
if (result.contains(words[i])) {
break;
}
if (words[i].charAt(0) == board[j][k]) {
boolean isVisited[][] = new boolean[board.length][board[0].length];
for (boolean a[] : isVisited) {
Arrays.fill(a, false);
}
if (dfs(j, k, words[i], 0, board, isVisited)) {
result.add(words[i]);
}
}
}
}
}
return result;
}
boolean dfs(int row, int col, String word, int index, char[][] board, boolean[][] isVisited) {
if (index == word.length()) {
return true;
} else if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || isVisited[row][col] || board[row][col] != word.charAt(index)) {
return false;
} else {
System.out.println(word.charAt(index) + " = " + index);
isVisited[row][col] = true;
return dfs(row + 1, col, word, index + 1, board, isVisited)
|| dfs(row, col + 1, word, index + 1, board, isVisited)
|| dfs(row - 1, col, word, index + 1, board, isVisited)
|| dfs(row, col - 1, word, index + 1, board, isVisited);
}
}
}
输入:
[["a","b","c"],["a","e","d"],["a","f","g"]]
["abcdefg","gfedcbaaa","eaabcdgfa","befa","dgc","ade"]
我的输出:
["abcdefg","gfedcbaaa","befa"]
预期的:
["abcdefg","befa","eaabcdgfa","gfedcbaaa"]