不多bb,直接看代码
public class RobotMovingScopeCount {
public static void main(String[] args) {
/*
*注意:对于矩阵问题,创建一个与矩阵相同的二维数组作为辅助变量是常见做法
*/
//传入参数
int threshold = 15;
int rows = 20;
int cols = 20;
//使用二维数组保存机器人经过的格子
int[][] blocksPassed = new int[rows][cols];
//将二维数组所有元素初始化为-1
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
blocksPassed[i][j] = -1;
}
}
countWithDFS(blocksPassed,threshold,rows,cols,0,0);
//统计blocksPassed中值为1的元素数目,即为符合要求的格子数
int count = 0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(blocksPassed[i][j] == 1){
count += 1;
}
}
}
System.out.println(count);
}
/*
*DFS策略:
*dfs(){
* 第一步,检查下标
* 第二步,检查是否被访问过,或者是否满足当前匹配条件
* 第三步,检查是否满足返回结果条件
* 第四步,都没有返回,说明应该进行下一步递归,步骤:标记、dfs()、回溯
* }
*/
public static boolean countWithDFS(int[][] blocksPassed,int threshold, int rows, int cols, int i, int j){
//递归终止条件
if(i<0 || rows <= i || j<0 || cols <= j){
return true;
}
if(blocksPassed[i][j] == 1){
return true;
}
if((sumOfInteger(i)+sumOfInteger(j)) > threshold){
return true;
}
//格子(i,j)满足要求,将blocksPassed[i][j]标记为1
blocksPassed[i][j] = 1;
//下一级递归
return countWithDFS(blocksPassed,threshold,rows,cols,i+1,j)&&
countWithDFS(blocksPassed,threshold,rows,cols,i-1,j)&&
countWithDFS(blocksPassed,threshold,rows,cols,i,j+1)&&
countWithDFS(blocksPassed,threshold,rows,cols,i,j-1);
}
public static int sumOfInteger(int num){
int num1 = num/1000;
int num2 = (num%1000)/100;
int num3 = (num%100)/10;
int num4 = num%10;
return num1+num2+num3+num4;
}
}
以上均为个人见解,如有谬误,欢迎指正!