题目:
题目链接
思路:
矩阵中找一条路径,使用嵌套循环假设每个位置都是一个起点
求解是否存在路径:
使用递归,根据题目描述,每一步可以走4个方向,所以4个方向都走,判断是否有解
有解的条件:1.当前值和要寻找的值相等且当前值未被访问过, 2.当前值是最后一个要寻找的值
有了以上思路,很快可以写出递归,注意递归结束条件以及可以适当“剪枝”
递归结束条件需要判断当前位置是否越界
剪枝的内容包括只要有任意一个方向有解,即可返回true,不需要继续求解因为题目不要求求所有路径
综上,使用一个bool二维数组表示当前位置是否被遍历过,注意!!结束递归本层的是否要把遍历过的标志信息恢复为false
代码:
public class Solution {
boolean[][] marked;
/**
*
* @param matrix 数据数组,题目给成一个一维的
* @param rows 行数
* @param cols 列数
* @param str 要寻找的字符串,题目给成一个一维数组
* @return
*/
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
if (matrix == null || matrix.length == 0){
return false;
}
//当前要寻找哪个字符
int index = 0;
marked = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (process(matrix, rows, cols, str, i, j, index)){
return true;
}
}
}
return false;
}
public boolean process(char[] matrix, int rows, int cols, char[] str, int i, int j, int index){
//判断是否越界
if (i < 0 || i >= rows || j < 0 || j >= cols || index >= str.length){
return false;
}
//二维行,列在一维数组上的对应下标关系
if (!marked[i][j] && matrix[i*cols+j] == str[index]){
if (index == str.length-1){
return true;
}
marked[i][j] = true;
index++;
boolean next1;
boolean next2;
boolean next3;
boolean next4;
//向左
next1 = process(matrix, rows, cols, str, i, j-1, index);
if (next1){
return true;
}
//向上
next2 = process(matrix, rows, cols, str, i-1, j, index);
if (next2){
return true;
}
//向右
next3 = process(matrix, rows, cols, str, i, j+1, index);
if (next3){
return true;
}
//向下
next4 = process(matrix, rows, cols, str, i+1, j, index);
if (next4){
return true;
}
//恢复标志位
marked[i][j] = false;
return false;
}else {
return false;
}
}
}
参数示例: