/**
* 矩阵中的距离:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
* 首先对所整个矩阵遍历,找到第一个字符,然后向上下左右查找下一个字符,由于每个字符都是相同的判断方法
* (先判断当前字符是否相等,再向四周查找),因此采用递归函数。由于字符查找过后不能重复进入,
* 所以还要定义一个与字符矩阵大小相同的布尔值矩阵,进入过的格子标记为true。如果不满足的情况下,
* 需要进行回溯,此时,要将当前位置的布尔值标记回false。(所谓的回溯无非就是对使用过的字符进行标记和处理后的去标记)
*
* @Description
*/
public class Test10 {
public boolean exist(char[][] board, String word) {
if (board == null || board.length < 1 || board[0].length < 1 || word == null) return false;
//矩阵的行号和列号
int rows = board.length - 1;
int cols = board[0].length - 1;
//记录已经访问过的位置
boolean[] visit = new boolean[rows*cols];
int pathLength = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (existCore(board,rows,cols,i,j,word,pathLength,visit)){
return true;
}
}
}
return false;
}
private boolean existCore(char[][] board, int rows, int cols, int i, int j, String word, int pathLength, boolean[] visit) {
boolean hasPath = false;
if ((i >= 0) && (i < rows) && (j >= 0) && (j < cols) && board[(i * cols) + j].equals(word.charAt(pathLength)) && !visit[i * cols + j]){
++pathLength;
visit[i*cols + j] = true;
hasPath = existCore(board, rows, cols, i - 1, j, word, pathLength + 1, visit)
|| existCore(board, rows, cols, i + 1, j, word, pathLength + 1, visit)
|| existCore(board, rows, cols, i, j - 1, word, pathLength + 1, visit)
|| existCore(board, rows, cols, i, j + 1, word, pathLength + 1, visit);
if (!hasPath){
--pathLength;
visit[i*cols + j] = false;
}
}
return hasPath;
}
public static void main(String[] args) {
}
}
剑指Offer-09-矩阵中的距离
最新推荐文章于 2024-01-09 19:09:51 发布