/*
题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
*/
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
/*
解题思路:采用回溯法,通过深度优先遍历,求得解
*/
int[][] flage=new int[rows][cols];//用于标记该格子是否被走过
return DFS(0,0,rows,cols,flage,threshold);
}
//深度优先(DFS)
public int DFS(int i,int j,int rows,int cols,int[][] flage,int threshold){
/*如果行小于0或者列小于0直接返回,如果行或列大于给定的行与列直接返回,如果行和列的各位之和大于给定的数,
直接返回,如果该点已经访问过了,则直接返回
*/
if(i < 0 || i >= rows || j < 0 || j >= cols || sum(i) + sum(j) > threshold || flage[i][j] == 1){
return 0;
}
flage[i][j] = 1;//表示访问过了
return DFS(i - 1, j, rows, cols, flage, threshold)
+ DFS(i + 1, j, rows, cols, flage, threshold)
+ DFS(i, j - 1, rows, cols, flage, threshold)
+ DFS(i, j + 1, rows, cols, flage, threshold)
+ 1;
}
//求出一个数各个位置上的和
public int sum(int num){
int result=0;
while(num>0){
int temp=num%10;
result+=temp;
num/=10;
}
return result;
}
}