对于有保存价值的题目,都会把代码贴上来。防止电脑里的丢失。
package jianzhiOffer;
/*
* 注意:递归结束的条件一定要写
*
* 自己的思路:利用图的思想,不断转换当前结点,对当前结点进行判断,直到最后。
*/
public class StringPathInMatrix {
private final int[][] next = new int[][] {{0, -1}, {0, 1}, {1, 0},{-1, 0}};
int rows;
int cols;
public boolean path(char[] array, 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[][] matrix = bulidMatrix(array);
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
if(tracking(matrix, str, marked, 0, i, j)) {
return true;
}
}
}
return false;
}
public boolean tracking(char[][] matrix, char[] str, boolean[][] marked,
int pathLen, int r, int c) {
if(pathLen == str.length)
return true;
if(r<0||c<0||r>rows-1||c>cols-1||str[pathLen]!=matrix[r][c]||marked[r][c]) {
return false;
}
marked[r][c] = true;
for(int[] n : next) {
if(tracking(matrix, str, marked, pathLen+1, r+n[0], c+n[1]))
return true;
}
return false;
}
public char[][] bulidMatrix(char[] array) {
char[][] matrix = new char[rows][cols];
int len = 0;
for(int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
matrix[i][j] = array[len++];
}
}
return matrix;
}
public static void main(String[] args) {
StringPathInMatrix p = new StringPathInMatrix();
char[] array = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l'};
char[] str= new char[] {'c', 'f', 'e', 'h', 'k'};
int r = 4;
int c = 3;
boolean IsPath = p.path(array, r, c, str);
System.out.println(IsPath);
}
}