package question13_机器人运动范围;
/**
* @Classname Main
* @Description TODO
* @Date 2020/4/11 16:47
* @Created by mmz
*/
public class Main {
static int Moving(int threshold,int rows,int cols){
if(threshold<0|| rows<0||cols<0){
return 0;
}
boolean[] visit = new boolean[rows*cols];
int count = Core(threshold,rows,cols,0,0,visit);
return count;
}
static int Core(int threshold,int rows,int cols,int i ,int j,boolean[] visit){
int count = 0;
if(cheak(threshold,rows,cols,i,j,visit)){
visit[j*rows+i] = true;
count = 1+Core(threshold,rows,cols,i+1,j,visit)
+Core(threshold,rows,cols,i-1,j,visit)
+Core(threshold,rows,cols,i,j+1,visit)
+Core(threshold,rows,cols,i,j-1,visit);
}
return count;
}
static boolean cheak(int threshold,int rows,int cols,int i ,int j,boolean[] visit){
if(!visit[j*rows+i] && i>=0 &&i<rows &&j>=0 && j<cols && getDigit(i)+getDigit(j) <=threshold){
return true;
}
return false;
}
static int getDigit(int i){
int sum = 0;
while(i>0){
sum += i%10;
i /=10;
}
return sum;
}
public static void main(String[] args) {
System.out.println(Moving(18, 40, 40));
}
}
有四个函数
第一个为启动函数
第二个为核心函数
第三个、四个都是辅助函数
第三个用来判断是否能进入该点,第四个用来当前位置的各位数和是否小于等于阻拦的位置。
核心函数来判断从(x,y)来是遍历。每次进入格子要更新当前布尔类型数组visit,最后用深度遍历遍历整个放格,返回能去到的个数。