题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
public class Solution {
int row=0;
int col=0;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
int[] array=new int[rows*cols];
boolean right = false;
row=rows;
col=cols;
if (str.length==0) return true;
if (matrix.length==0) {
return false;
}
for (int i = 0; i < matrix.length; i++) {
if (matrix[i]==str[0]) {
right = compare(i/col, i%col, matrix, str,0,array);
if(right) return true;
}
}
return false;
}
public boolean compare(int now_rows, int now_cols, char[] matrix, char[] str, int index, int[] array) {
// System.out.println(col+" "+ row);
int k = now_rows * col + now_cols;
if (now_cols < 0 || now_cols >= col || now_rows < 0 || now_rows >= row || array[k] == 1
|| matrix[k] != str[index]) {
return false;
}
if (index == str.length - 1)
return true;
array[k] = 1;
if (compare(now_rows - 1, now_cols, matrix, str, index + 1, array)// 上
|| compare(now_rows + 1, now_cols, matrix, str, index + 1, array)// 下
|| compare(now_rows, now_cols - 1, matrix, str, index + 1, array)// 左
|| compare(now_rows, now_cols + 1, matrix, str, index + 1, array)) {// 右
return true;
}
array[k] = 0;
return false;
}
}
int row=0;
int col=0;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
int[] array=new int[rows*cols];
boolean right = false;
row=rows;
col=cols;
if (str.length==0) return true;
if (matrix.length==0) {
return false;
}
for (int i = 0; i < matrix.length; i++) {
if (matrix[i]==str[0]) {
right = compare(i/col, i%col, matrix, str,0,array);
if(right) return true;
}
}
return false;
}
public boolean compare(int now_rows, int now_cols, char[] matrix, char[] str, int index, int[] array) {
// System.out.println(col+" "+ row);
int k = now_rows * col + now_cols;
if (now_cols < 0 || now_cols >= col || now_rows < 0 || now_rows >= row || array[k] == 1
|| matrix[k] != str[index]) {
return false;
}
if (index == str.length - 1)
return true;
array[k] = 1;
if (compare(now_rows - 1, now_cols, matrix, str, index + 1, array)// 上
|| compare(now_rows + 1, now_cols, matrix, str, index + 1, array)// 下
|| compare(now_rows, now_cols - 1, matrix, str, index + 1, array)// 左
|| compare(now_rows, now_cols + 1, matrix, str, index + 1, array)) {// 右
return true;
}
array[k] = 0;
return false;
}
}