地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
析:就是判断从(0,0)能到达的点的数目。
法1:别人的递归方法
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
int flag[][] = new int[rows][cols]; //记录是否已经走过
return helper(0, 0, rows, cols, flag, threshold);
}
private int helper(int i, int j, int rows, int cols, int[][] flag, int threshold) {
if (i < 0 || i >= rows || j < 0 || j >= cols || numSum(i) + numSum(j) > threshold || flag[i][j] == 1) return 0;
flag[i][j] = 1;
return helper(i - 1, j, rows, cols, flag, threshold)
+ helper(i + 1, j, rows, cols, flag, threshold)
+ helper(i, j - 1, rows, cols, flag, threshold)
+ helper(i, j + 1, rows, cols, flag, threshold)
+ 1;
}
private int numSum(int i) {
int sum = 0;
do{
sum += i%10;
}while((i = i/10) > 0);
return sum;
}
}
法2:自己的非递归方法
每次求与(0,0)距离依次是1、2、3 ..可以到达的点放在list中,下一轮是由上一轮中的点求出的。
import java.util.ArrayList;
import java.util.List;
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
if(rows==0 || cols==0 || threshold<0)
return 0;
int[][] pass = new int[rows][cols];
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
pass[i][j]=canPass(i, j, threshold);
boolean[][] vis = new boolean[rows][cols];
List<Point> list = new ArrayList<>();
List<Point> list2 = new ArrayList<>();
list.add(new Point(0, 0));
int num=1;
vis[0][0]=true;
while(!list.isEmpty()){
list2.clear();
for(int i=0;i<list.size();i++){
Point p =list.get(i);
// left
if(p.y>=1 && pass[p.x][p.y-1]==1 && !vis[p.x][p.y-1]){
num++;
vis[p.x][p.y-1]=true;
list2.add(new Point(p.x, p.y-1));
}
// right
if(p.y<=cols-2 && pass[p.x][p.y+1]==1 && !vis[p.x][p.y+1]){
num++;
vis[p.x][p.y+1]=true;
list2.add(new Point(p.x, p.y+1));
}
// up
if(p.x>=1 && pass[p.x-1][p.y]==1 && !vis[p.x-1][p.y]){
num++;
vis[p.x-1][p.y]=true;
list2.add(new Point(p.x-1, p.y));
}
// down
if(p.x<=rows-2 && pass[p.x+1][p.y]==1 && !vis[p.x+1][p.y]){
num++;
vis[p.x+1][p.y]=true;
list2.add(new Point(p.x+1, p.y));
}
}
list.clear();
list.addAll(list2);
}
return num;
}
public static int canPass(int x,int y,int k){
int sum=0;
while(x>0){
sum+=(x%10);
x/=10;
}
while(y>0){
sum+=(y%10);
y/=10;
}
return sum<=k?1:0;
}
}
class Point{
int x,y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}