/*
* 面试题13:机器人的运动范围
* 题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,
* 每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
* 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
* 但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
* 思路:回溯法.基本思路和上一题的矩阵路径一样.用一个flag矩阵记录每个格子是否被走过.
* 走过了就不会再走.用一个全局变量sun记录走过的符合要求的格子数.
* 从0,0点开始,每步判断是否符合条件,符合条件则往他的上下左右走且sum++,
* 否则返回.每一步都要把走过的格子标记,保证之后不会再经过.
*/
public class No13movingCount {
public static void main(String[] args) {
No13movingCount n = new No13movingCount();
int th = 18;
int rows = 45;
int cols = 38;
int sum = n.movingCount(th, rows, cols);
System.out.println(sum);
}
int sum = 0;
public int movingCount(int threshold, int rows, int cols) {
if (threshold <= 0) {
return 0;
}
int[] flag = new int[rows * cols];
moving(threshold,rows,cols,0,0,flag);
return sum;
}
private boolean moving(int threshold, int rows, int cols, int i, int j, int[] flag) {
int index = i * cols + j;//将二维坐标映射到一维数组里面
if (i < 0 || j < 0 || i >= rows || j >= cols || flag[index] == 1)//flag==1表示已经走过这个点了
return false;
int sumOfI = sumOfNumber(i);
int sumOfJ = sumOfNumber(j);
flag[index] = 1;//走过的格子置为1
if (sumOfI + sumOfJ <= threshold) {
sum++;//当前位置坐标符合门槛值要求,记录之
} else {
return false;//超过门槛值的路径也不会再往后走
}
moving(threshold,rows,cols,i+1,j,flag);// 往当前位置的上下左右去探索
moving(threshold,rows,cols,i,j+1,flag);
moving(threshold,rows,cols,i-1,j,flag);
moving(threshold,rows,cols,i,j-1,flag);
return false;
}
//计算位数之和
private int sumOfNumber(int i) {
int sum = 0;
while (i > 0) {
sum += i%10;
i /=10;
}
return sum;
}
}