题目:地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每一次可以向左右上下移动一格,但不能进入行坐标和列坐标之和大于K的格子。例如,当k为18的时,机器人能够进入的方格(35,37),因为3+5+3+7=18.但是它不能进入方格(35,38),因为3+5+3+8=19。请问该机器人能够到达多少个格子?
分析:本质上是和前面矩阵中的路径一样的问题,都是利用回溯法来实现。
#include<stdio.h>
int getDigitSum(int number)
{
int sum = 0;
while(number > 0)
{
sum += number % 10;
number /= 10;
}
return sum;
}
int check(int temp, int rows, int cols, int row, int col, int *visited)
{
if(row >= 0 && row < rows && col >= 0 && col < cols
&& getDigitSum(row) + getDigitSum(col) <= temp
&& !visited[row * cols + col])
return 1;
return 0;
}
int movingCountCore(int temp, int rows, int cols,
int row, int col, int *visited)
{
int count = 0;
if(check(temp, rows, cols, row, col, visited))
{
visited[row * cols + col] = 1;
count = 1 + movingCountCore(temp, rows, cols,
row - 1, col, visited)
+ movingCountCore(temp, rows, cols,
row, col - 1,visited)
+ movingCountCore(temp, rows, cols,
row + 1, col, visited)
+ movingCountCore(temp, rows, cols,
row, col + 1, visited);
}
return count;
}
int movingCount(int temp, int rows, int cols)
{
if(temp < 0 || rows <= 0 || cols <= 0)
return 0;
int *visited[rows * cols];
int i;
for(i = 0; i < rows * cols; ++i)
visited[i] = 0;
int count = movingCountCore(temp, rows, cols, 0, 0, visited);
return count;
}
int main(int argc, char* argv[])
{
int temp,rows,cols;
printf("enter three numbers for temp,rows,cols:");
scanf("%d %d %d",&temp,&rows,&cols);
printf("能够到达的格子数为:%d!\n",movingCount(temp,rows,cols));
return 0;
}