题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
碰到这种题毫无疑问就是动态规划或者递归。接下来就是考虑出口入口。
1》出口可以由题目得当坐标和大于k值时,当该方格被移动过的时候,当坐标大小超过m行和n列的方格坐标范围时,皆返回0.
2》除了这些情况就是向左,右,上,下四个方向移动一格。
3》还是设计一个tag标签数组来记录该方格是否被走过。
代码
class Solution {
public:
//int movepath(int threshold, int r, int c,int *tag);
int movingCount(int threshold, int rows, int cols)
{
m = rows, n = cols;
int *tag=new int[rows*cols];//标签数组
memset(tag, 0, rows * cols);//初始化标签数组为0
if (rows == 0 || cols == 0)
return 0;
return movepath(threshold, 0, 0, tag);
delete []tag;//防止内存泄露
}
int movepath(int threshold, int r, int c, int* tag) {
//计算坐标和。
int sum = 0;
int tmpr = r, tmpc = c;
while (tmpr > 0 ) {
sum += tmpr % 10;
tmpr = tmpr / 10;
}
while (tmpc > 0) {
sum += tmpc % 10;
tmpc = tmpc / 10;
}
//出口可以由题目得当坐标和大于k值时,当该方格被移动过的时候,当坐标大小超过m行和n列的方格坐标范围时,皆返回0.
if (sum > threshold || r < 0 || c < 0 || r >= m || c >= n|| tag[r * n + c] ==1)
return 0;
//向左,右,上,下四个方向移动一格。
tag[r * n + c]=1;//表示这个方格走过
return movepath(threshold, r - 1, c, tag) + movepath(threshold, r, c - 1, tag) + movepath(threshold, r + 1, c, tag) + movepath(threshold, r, c + 1, tag) + 1;
}
private:
int m, n;//表示m行和n列的方格。减少函数参数数量。
};