判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向上下左右移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
首先将一维数组化为二维数组,然后遍历,比较值是否是字符串那个值,设有标记数组。
public class Solution {
private final static int[][] next={{0,-1},{0,1},{-1,0},{1,0}};
private int rows;
private int cols;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
if(rows==0||cols==0) return false;
this.rows = rows;
this.cols= cols;
boolean[][] marked = new boolean[rows][cols];
char[][] array = buildMatrix(matrix);
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(backtracking(array,str,marked,0,i,j))
return true;
}
}
return false;
}
private boolean backtracking(char[][] matrix,char[] str,
boolean[][] marked,int pathLen,int r,int c){
if(pathLen == str.length) return true;
//下面加判断,二维数组的那个值是不是字符串当中对应的值
if(r<0||r>=rows||c<0||c>=cols
||matrix[r][c]!=str[pathLen] || marked[r][c]){
return false;
}
marked[r][c] = true;
for(int[] n:next){
if(backtracking(matrix,str,marked,pathLen+1,r+n[0],c+n[1])){
return true;
}
}
marked[r][c]=false;
return false;
}
private char[][] buildMatrix(char[] array){
char[][] matrix = new char[rows][cols];
for(int r=0, idx =0;r<rows;r++){
for(int c =0;c<cols;c++){
matrix[r][c] = array[idx++];
}
}
return matrix;
}
}
里面有在二维数组里面遍历:
1.foreach是java的一个语法糖,就是让你解放双手少做无用功;
2.foreach的作用,举个简单的例子:
(省略类及main方法)
int arr[]=new arr[5];
for(int i=0; i<5; ++i)
{System.out.println(arr[i]);}
这里的for循环等价于:
for(int x: arr){System.out.println(x) ;}
一个一维数组遍历二维数组的每一项,一维数组每次只有两个参数。
其中写的错误:next没有定义final、static、int属性
变量也没有定义属性,this后面没有加点,for循环内i和j没有定义属性,条件判断内的等号只有一个,代码括号顺序改变,没有返回return。
其中,新建立的boolean是默认值为false,建立Boolean则是默认值为null,它是boolean的对象类。