题目:
地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向上、下、左、右移动一个格子,但不能进入进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(37,35),因为3+7+3+5 =18.但它不能进入方格(35,38),因为3+5+3+8=19.请问机器人能够到达多少个格子?
测试用例:
1.格子全部都在范围内;
2.格子中的部分在范围内;
3.特殊输入(格子都不在范围内,k为负数)
解题思路:
机器人从坐标(0,0)开始移动。当它进入坐标(i,j)的矩阵时,通过检测(check)坐标的位数和来判断机器人是否能够进入。如果机器人能够进入坐标为(i,j)的格子,则继续判断是否能够进入与之相连的4个格子(i,j-1)、(i,j+1)、(i-1,j)和(i+1,j)。因此,我们可以使用回溯算法来进行计算。
程序代码:
moving.c:
//moving.c
#include "moving.h"
//运动函数
int GetDigitSum(int number){
int sum = 0;
while(number>0){
sum += number%10;
number /= 10;
}
return sum;
}
int check(int threshold,int rows,int cols,int row,int col,int * visited){
if(row>=0 && row<rows && col>=0 && col<cols && GetDigitSum(row)+GetDigitSum(col)<= threshold && (visited[row*cols+col] == 0)){
return 1;
}
return 0;
}
int movingCountCore(int threshold,int rows,int cols,int row,int col,int* visited){
int count = 0;
if(check(threshold,rows,cols,row,col,visited)){
visited[row*cols+col] = 1;
count = 1+ movingCountCore(threshold,rows,cols,row-1,col,visited)\
+movingCountCore(threshold,rows,cols,row,col-1,visited)\
+movingCountCore(threshold,rows,cols,row+1,col,visited)\
+movingCountCore(threshold,rows,cols,row,col+1,visited);
}
return count;
}
int movingCount(int threshold,int rows,int cols){
if(threshold<0||rows<=0||cols<=0){
return 0;
}
int * visited = (int *)malloc(sizeof(int)*rows*cols);
//for(int i = 0; i<cols*rows;++i){
// visited[i] = 0;//初始化
//}
memset(visited,0,rows*cols);
int count = movingCountCore(threshold,rows,cols,0,0,visited);
free(visited);
return count;
}
moving.h:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int movingCount(int threshold,int rows,int cols);
int movingCountCore(int threshold,int rows,int cols,int row,int col,int* visited);
int GetDigitSum(int number);
int check(int threshold,int rows,int cols,int row,int col,int * visited);
测试用例代码:
//主函数
int main(){
//全部都在范围内
int count = movingCount(18,5,5);
printf("count expect:25 actual:%d\n",count);
//部分在范围内
count = movingCount(9,9,9);
printf("count expect:53 actual:%d\n",count);
//全部不在范围内
count = movingCount(-5,18,18);
printf("count expect:0 actual:%d\n",count);
return 0;
}
显示结果: