题目:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路:
回溯法:
从(0,0)开始走,每成功走一步,就标记当前的位置为true,然后从上、下、左、右四个方向探索,直到访问完矩阵中所有的格子为止;
1、要求矩阵的格子不能重复进入,还需要定义一个跟字符矩阵同样大小的布尔矩阵,用来标识路径是否已经进入过该格子;
2、当矩阵中坐标为(row,col)的格子满足条件时,对4个相邻的格子(row,col-1),(row-1,col),(row,col+1)以及(row+1,col)进行下一步的判断
判断的条件:
(1)当前格子在矩阵内;
(2)当前格子对应坐标的位数和在阈值范围内;
(3)当前格子没有被访问过。
程序:
public class subject66 {
public static int movingCount(int threshold, int rows, int cols) {
if(threshold < 0 || rows <= 0 || cols <= 0) {
return 0;
}
boolean[][] visited = new boolean[rows][cols];
return moving(threshold, 0, rows, 0, cols, visited);
}
public static int moving(int threshold, int row, int rows, int col, int cols, boolean[][] visited) {
if(row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || (sum(row) + sum (col)) > threshold) {
return 0;
}
visited[row][col] = true;//标记当前格子被走过
return moving(threshold, row - 1 , rows, col, cols, visited) //上、下、左、右
+ moving(threshold, row + 1, rows, col, cols, visited)
+ moving(threshold, row , rows, col - 1, cols, visited)
+ moving(threshold, row , rows, col + 1, cols, visited)
+ 1;
}
public static int sum(int num) {
int result = 0;
while(num != 0) {
result += num % 10;
num = num / 10;
}
return result;
}
public static void main(String args[]) {
System.out.println(movingCount(5, 10, 10));
}
}