动态规划之机器人的移动范围的回溯算法心得
要想解决这个问题首先要理清思路
题目:地上有一个M行N列的方格,一个机器人从坐标0,0的格子开始移动,每次可以向左右上下移动一格,但不能进入航坐标和列坐标的位数之和,大于K的格子列入,当K为18时,机器人能够进入方格35 ,37,因为3+5+3+7=18,但它不能进入方格35 ,38,因为3+5+3+8=19,请问该机器人能够到达多少个格子?
首先,机器人得移动方格会受限制不能大于行坐标和列坐标得位数之和;因此首先要计算出各个位上得数然后求和,这里我定义了一个函数getNumber(int n) 来获取位数和;
public int getNumber(int n){
int res = 0;
if(n>0){
res = res+n%10;
n=n/10;
}
return res;
}
第二点,如果某行某列已经走过了,那么我们就要标记一下;我定义了一个布尔数组来存储标记;
boolean[] visit =new boolean[rows*cows];
第三点,要通过校验,获取当前的下一个遍历路径,通过check()来实现;
public boolean check(int threshold,int rows,int cols,int row,int col,boolean[] visit){
if(row>=0&&row<rows&&col>=0&&col<cols&&(getNumber(row)+getNumber(col))<=threshold && !visit[row*cols+col]){
return true;
}
return false;
}
结合上述步骤,可以完美解决问题;代码如下;
public class Demo {
public static void main(String[] args) {
int rows =50;
int cows =50;
int num = 62;
Demo sb = new Demo();
System.out.println(sb.movingCount(num, rows, cows));
}
int getNumber(int n){
int res = 0;
if(n>0){
res = res+n%10;
n=n/10;
}
return res;
}
public int movingCount(int threshold, int rows, int cols) {
if(threshold<0||rows<=0||cols<=0) return 0;
boolean[] visit = new boolean[rows*cols];
for (int i=0;i<rows*cols;i++){
visit[i] = false;}
int count = movinggo(threshold, rows, cols, 0, 0, visit);
return count;
}
public int movinggo(int threshold,int rows,int cols,int row,int col,boolean[] visit){
int count = 0;
if(check(threshold, rows, cols, row, col, visit)){
visit[row*cols+col]=true;
count= 1+movinggo(threshold, rows, cols, row+1, col, visit)
+movinggo(threshold, rows, cols, row, col-1, visit)
+movinggo(threshold, rows, cols, row-1, col, visit)
+movinggo(threshold, rows, cols, row, col+1, visit);
}
return count;
}
public boolean check(int threshold,int rows,int cols,int row,int col,boolean[] visit){
if(row>=0&&row<rows&&col>=0&&col<cols&&(getNumber(row)+getNumber(col))<=threshold && !visit[row*cols+col]){
return true;
}
return false;
}
}
缺点:如果行和列很大,递归会非常慢,程序可能会崩溃;