题目描述:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
测试用例:
1)功能测试(方格多行多列;k为正数)
2)边界值测试(方格只有一行或者一列;k等于0)
3)特殊输入测试(k为负数;方格为空nullptr)
解题思路:
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(threshold<0 || rows<0 || cols<0)return 0; //不要忘记判断矩阵大小 使用||,而不是&&
//是否能到达节点(row,col),可以到达的标记为true
bool* visited = new bool[rows*cols];
memset(visited,0,rows*cols);
int count = move(threshold, rows, cols, visited,0,0);
//count = sumFlags(visited, rows, cols);
delete[] visited;
return count;
}
//递归的终止条件是:不满足if终止递归,返回0
int move(int threshold, int rows, int cols, bool* visited, int row,int col)
{
int count = 0; //定义在函数内部!!!
//判断机器人是否能进入到坐标为(row,col)的方格。机器人能到达该方格,count加1
if(row>=0 && row<rows && col>=0 && col<cols
&& (computeBit(row, col)<=threshold) && visited[row*cols+col]==false) {
visited[row*cols+col]=true;
//为什么使用加法?
//能进入if,说明能从(0,0)进入(row,col),因此count = 1+ (...)
//(row,col)可进入,在四周同时查找上下左右是否还有能进入的节点。
count = 1 + move( threshold, rows, cols, visited, row, col-1)
+ move( threshold, rows, cols, visited, row, col+1)
+ move( threshold, rows, cols, visited, row-1, col)
+ move( threshold, rows, cols, visited, row+1, col);
}
return count;
}
int computeBit( int row, int col)
{
return sumBit(row)+sumBit(col);
}
int sumBit(int n)
{
int sum = 0;
while(n){ //while(n>0)
sum+=(n%10);
n=n/10;
}
return sum;
}
//private:
//int count = 0; //count不可以定义在这里
};