AcWing打卡活动
《剑指Offer》打卡活动
周一第十一题 矩阵中的路径
class Solution {
public boolean hasPath(char[][] matrix, String str) {
if(matrix == null || str == null || matrix.length <= 0) {
return false;
}
// 标记所有格子的状态,判断机器人是否走过
Boolean[] visited = new Boolean[matrix.length * matrix[0].length];
// 置数组所有元素为false
visited = memset(visited);
char[] charArr = str.toCharArray();
int pathLength = 0; // 记录已到达字符串索引的位置
// 二维数组中的每个元素都需要遍历到,机器人可以从任意位置出发
for(int row = 0; row < matrix.length; row++) {
for(int col = 0; col < matrix[row].length; col++) {
if(hasPathCore(matrix, row, col, charArr, pathLength, visited)) {
return true;
}
}
}
return false;
}
public Boolean hasPathCore(char[][] matrix, int row, int col, char[] charArr,
int pathLength, Boolean[] visited) {
int rows = matrix.length;
int cols = matrix[0].length;
if(charArr.length == pathLength) {
return true;
}
Boolean hasPath = false;
if(row >= 0 && row < rows && col >= 0 && col < cols
&& matrix[row][col] == charArr[pathLength] && !visited[row * cols + col]) {
++pathLength;
visited[row * cols + col] = true; // 置当前格子为走过的格子
// 继续遍历该格子的下、上、左、右边
hasPath = hasPathCore(matrix, row + 1, col, charArr, pathLength, visited)
|| hasPathCore(matrix, row - 1, col, charArr, pathLength, visited)
|| hasPathCore(matrix, row, col - 1, charArr, pathLength, visited)
|| hasPathCore(matrix, row, col + 1, charArr, pathLength, visited);
// 如果未匹配到路径,则退回
if(!hasPath) {
--pathLength;
visited[row * matrix[0].length + col] = false;
}
}
return hasPath;
}
public Boolean[] memset(Boolean[] arr) {
for(int i = 0; i < arr.length; i++) {
arr[i] = false;
}
return arr;
}
}