地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左,右,上,下移动一格子,单不能进入坐标位数之和大于k的格子,最终机器人能够到达多少个格子。
这个方格可以看成m x n的矩阵。除矩阵边界上的格子外,其它格子都有4个相邻的格子。利用回溯法,机器人从坐标(0,0)开始移动,当它进入坐标为(i,j)的格子时,通过检查坐标的位数和来判断机器人是否能够进入。如果机器人能够进入坐标为(i,j)的格子,count首先加1,再判断它能否进入四个相邻的格子(i,j-1),(i-1,j),(i,j+1),(i+1,j)。重复这个过程,直到坐标位数之和不大于k的格子被遍历完为止,最终返回count。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
//判断一个数字位数之和
int getDigSum(int num)
{
int sum = 0;
while (num > 0)
{
sum += num % 10;
num /= 10;
}
return sum;
}
//判断能否进入格子
bool check(int themax, int rows, int cols, int row, int col, bool* visit)
{
if (row >= 0 && row < rows&&col >= 0 && col <= cols&&getDigSum(row) + getDigSum(col) <= themax&&!visit[row*cols + col])
{
return true;
}
return false;
}
int movingCount2(int themax, int rows, int cols, int row, int col,bool* visit)
{
int count = 0;
if (check(themax, rows, cols, row, col, visit))
{
visit[row*cols + col] = true;
//遍历一个格子周围的四个格子
count = 1 + movingCount2(themax, rows, cols, row - 1, col, visit) +
movingCount2(themax, rows, cols, row , col-1, visit) +
movingCount2(themax, rows, cols, row + 1, col, visit) +
movingCount2(themax, rows, cols, row , col+1, visit);
}
return count;
}
int movingCount(int themax, int rows, int cols)
{
if (themax < 0 || rows <= 0 || cols <= 0)
{
return 0;
}
bool *visit = (bool*)malloc(rows*cols*sizeof(bool));
//数字初始化为false表明机器人为进入过这个格子
for (int i = 0; i < rows*cols; ++i)
{
visit[i] = false;
}
int count = movingCount2(themax, rows, cols, 0, 0, visit);
free(visit);
return count;
}