思路:
回溯法,每次由一个点向上下左右递归
注意的点:
- 1、结束标志,点超出区域或者当前扫描的位置已经到单词最后一个索引位置了
- 2、由于我们每次要进行点的上下左右遍历,我们要记录一下每条路上递归我们已经使用的点,这些点不能重复使用
代码:
class Solution {
private int rows;
private int cols;
private int wordLength;
private boolean[][] hasUse;
private char[] charArray;
private char[][] board;
public boolean exist(char[][] board, String word) {
rows = board.length;
if (rows == 0) {
return false;
}
cols = board[0].length;
wordLength = word.length();
charArray = word.toCharArray();
hasUse = new boolean[rows][cols];
this.board = board;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (dfs(i, j, 0)) {
return true;
}
}
}
return false;
}
private boolean dfs(int i, int j, int currCharIndex) {
//判断是否已使用,是否点在区域内
if (!isArea(i, j)||hasUse[i][j]){
return false;
}
//结束条件
if (currCharIndex == wordLength - 1) {
return board[i][j] == charArray[currCharIndex];
}
if (board[i][j] == charArray[currCharIndex]) {
//上下左右的尝试
hasUse[i][j] = true;
boolean res = dfs(i + 1, j, currCharIndex + 1) || dfs(i - 1, j, currCharIndex + 1)
|| dfs(i, j + 1, currCharIndex + 1) || dfs(i, j - 1, currCharIndex + 1);
if (res) {
return true;
}
hasUse[i][j] = false;
}
return false;
}
private boolean isArea(int i, int j) {
return i >= 0 && i < rows && j >= 0 && j < cols;
}
}