地上有一个 rows 行和 cols 列的方格。坐标从 [0,0] 到 [rows-1,cols-1] 。一个机器人从坐标 [0,0] 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 threshold 的格子。 例如,当 threshold 为 18 时,机器人能够进入方格 [35,37] ,因为 3+5+3+7 = 18。但是,它不能进入方格 [35,38] ,因为 3+5+3+8 = 19 。请问该机器人能够达到多少个格子?
方法一:
static int count = 0;
static int sum(int rows, int cols){
int sum_num = 0;
while(rows){
sum_num += rows % 10;
rows /= 10;
}
while(cols){
sum_num += cols % 10;
cols /= 10;
}
return sum_num;
}
static void able(char** mark, int rows, int cols, int threshold, int i, int j){
if(i<0 || i>= rows || j<0 || j>= cols || mark[i][j] || sum(i, j) > threshold) return;
count++;
mark[i][j] = 1;
able(mark, rows, cols, threshold, i-1, j);
able(mark, rows, cols, threshold, i+1, j);
able(mark, rows, cols, threshold, i, j-1);
able(mark, rows, cols, threshold, i, j+1);
}
int movingCount(int threshold, int rows, int cols ) {
char **mark = (char **)malloc(rows*sizeof(char*));
int i = 0, j = 0;
for(i=0;i<rows;i++){
mark[i] = (char *)malloc(cols*sizeof(char));
}
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
mark[i][j] = 0;
}
}
able(mark, rows, cols, threshold, 0, 0);
return count;
}
方法二:
static int sum(int rows, int cols){
int sum_num = 0;
while(rows){
sum_num += rows % 10;
rows /= 10;
}
while(cols){
sum_num += cols % 10;
cols /= 10;
}
return sum_num;
}
static int able(char** mark, int rows, int cols, int threshold, int i, int j){
if(i<0 || i>= rows || j<0 || j>= cols || mark[i][j] || sum(i, j) > threshold) return 0;
int count = 0;
mark[i][j] = 1;
count = 1 +
able(mark, rows, cols, threshold, i-1, j) +
able(mark, rows, cols, threshold, i+1, j) +
able(mark, rows, cols, threshold, i, j-1) +
able(mark, rows, cols, threshold, i, j+1);
return count;
}
int movingCount(int threshold, int rows, int cols ) {
char **mark = (char **)malloc(rows*sizeof(char*));
int i = 0, j = 0;
for(i=0;i<rows;i++){
mark[i] = (char *)malloc(cols*sizeof(char));
}
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
mark[i][j] = 0;
}
}
return able(mark, rows, cols, threshold, 0, 0);
}
两种方法相差不多,第二种方法给出了一种可以带返回值的递归,用加号连接之前没有碰到过