题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串”bcced”的路径,但是矩阵中不包含”abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
/**
* 矩阵中的路径
*
* @author 80769
*
*/
public class Twelve {
public final static int[][] next = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };
public int rows;
public int cols;
// 把一维数组转成二维数组
public char[][] buildMatrix(char[] array) {
char[][] matrix = new char[rows][cols];
for (int r = 0, index = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
matrix[r][c] = array[index++];
}
}
return matrix;
}
// 回溯
public 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;
}
// 判断是否有此字符串
public boolean hasPath(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 = buildMatrix(array);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (backtracking(matrix, str, marked, 0, i, j)) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
char[] array = { 'a', 'b', 't', 'g', 'c', 'f', 'c', 's', 'j', 'd', 'e', 'h' };
char[] str = { 'b', 'f', 'c', 'e' };
Twelve twelve = new Twelve();
boolean hasPath = twelve.hasPath(array, 3, 4, str);
System.out.println(hasPath);
}
}
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
/**
* 机器人的运动范围
*
* @author 80769
*
*/
public class Thirteen {
public int movingCount(int threshold, int rows, int cols) {
if (threshold == 0) {
return 0;
}
int[][] flag = new int[rows][cols];
return count(threshold, rows, cols, 0, 0, flag);
}
//机器人走过的点
private int count(int threshold, int rows, int cols, int i, int j, int[][] flag) {
if (i < 0 || j < 0 || i >= rows || j >= cols || sum(i) + sum(j) > threshold || flag[i][j] == 1) {
return 0;
}
flag[i][j] = 1;
return 1 + count(threshold, rows, cols, i - 1, j, flag) + count(threshold, rows, cols, i + 1, j, flag)
+ count(threshold, rows, cols, i, j - 1, flag) + count(threshold, rows, cols, i, j - 1, flag);
}
// 每点坐标的值
public int sum(int i) {
int s = 0;
while (i > 0) {
s += i % 10;
i /= 10;
}
return s;
}
}