这题同时也是剑指Offer第二版的第12题,我原来写的那个代码实在是太难看了。
在看了剑指Offer中的C++的代码后,我改写成了Java的代码。
这里是典型回溯思想,居然是的方式就是深度优先搜索。
https://leetcode-cn.com/problems/word-search/
任意一个元素都是可以开始的起点,所以,最起码一次每个元素一次遍历。
如果元素符合题目的要求,那么就开始判断它周围的四个元素是否满足要求,如果满足要求的话,就从这个元素继续往下走,当然我们需要要给一个记录是否走过的路径。
当然,知道思想和可以写出正确的代码是两码事,所以,我们来看看正确的代码。
class Solution {
private int rowNum = 0;
private int colNum = 0;
boolean[][] visited = null;
String word = null;
char[][] board = null;
public boolean exist(char[][] board, String word) {
// 判空操作。
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
rowNum = board.length;
colNum = board[0].length;
this.word= word;
this.board = board;
visited = new boolean[rowNum][colNum];
for (int i = 0; i < rowNum; ++i) {
for (int j = 0; j < colNum; ++j) {
if (existCore(i , j, 0 )) {
return true;
}
}
}
return false;
}
private boolean existCore(int row, int col, int index) {
if (index == word.length()) {
return true;
}
boolean hasPath = false;
if (row >= 0 && row < rowNum && col >= 0 && col < colNum && !visited[row][col]
&& word.charAt(index) == board[row][col]) {
++index;
visited[row][col] = true;
// 判断四个点中是否满足条件。
hasPath = existCore(row - 1, col, index)
|| existCore(row + 1, col, index)
|| existCore(row, col - 1, index)
|| existCore(row, col + 1, index);
// 如果四个点都没满足,那么就要退回上一个点,吧走过的点置为false
if (!hasPath) {
--index;
visited[row][col] = false;
}
}
return hasPath;
}
}
以上的代码,效果还不错。