本文共 1855 字,大约阅读时间需要 6 分钟。
public class Solution { public boolean hasPath(char[] matrix, int rows, int cols, char[] str){ boolean[] flag = new boolean[matrix.length]; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { if(judge(matrix, rows, cols, i, j, str, 0, flag)) { return true; } } } return false; } //matrix一维数组 rows矩阵的行 cols矩阵的列, 该点所在当前位置的行和列rowIndex colIndex str要寻找的字符串 k字符串的那个位置,flag该点有没有下过 public boolean judge(char[] matrix, int rows, int cols, int rowIndex, int colIndex, char[] str, int k, boolean[] flag) { //获取该点在一维数组中的位置 int index = rowIndex * cols + colIndex; //该点越界直接false if(rowIndex < 0 || rowIndex > rows - 1 || colIndex < 0 || colIndex > cols - 1) { return false; } //如果没有越界,该点还在矩阵中 //1.该点不等于对应字符串的点false if(matrix[index] != str[k]) { return false; } //2.该点走过false if(flag[index] == true) { return false; } //3.该点有没有下过,又相等 //3.1该点是字符串对应最后一个 if(k == str.length - 1) { //直接true return true; } //3.2该点不是最后一个,先记录该点下过,怕等下递归的时候往回找 flag[index] = true; //3.3递归 boolean ans = judge(matrix, rows, cols, rowIndex + 1, colIndex, str, k + 1, flag) || judge(matrix, rows, cols, rowIndex - 1, colIndex, str, k + 1, flag) || judge(matrix, rows, cols, rowIndex, colIndex - 1, str, k + 1, flag) || judge(matrix, rows, cols, rowIndex, colIndex + 1, str, k + 1, flag); if(ans == true) { return true; }else { flag[index] = false;//该点走不到终点,标记该点没走过,下次递归的时候该点还是可以走的 return false; } }}
转载地址:http://ivhzi.baihongyu.com/