机器人运动范围
题目
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
回溯法
count可以传入也可以累积
//找出下面代码里面的bug!
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(threshold<0 || rows<=0 || cols<=0)
return 0;
bool *visit = new bool[rows*cols];
memset(visit, false, rows*cols);
int count = movingCountCore(threshold, rows, cols, 0, 0, visit);
delete[] visit;
return count;
}
int movingCountCore(int threshold, int rows, int cols, int r, int c, bool* visit)
{
int count = 0;
if(r>=0 && r<rows && c>=0 && c<cols && !visit[r*rows+c]
&& (digitSum(r)+digitSum(c))<=threshold)
{
visit[r*rows+c] = true;
count = 1+movingCountCore(threshold, rows, cols, r+1, c, visit)
+movingCountCore(threshold, rows, cols, r-1, c, visit)
+movingCountCore(threshold, rows, cols, r, c+1, visit)
+movingCountCore(threshold, rows, cols, r, c-1, visit);
}
return count;
}
int digitSum(int num)
{
int sum = 0;
while(num>0)
{
sum += num%10;
num = num/10;
}
return sum;
}
};
//应该是 r*cols+c ,写错成了 r*rows+c
//ok
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(threshold<0 || rows<1 || cols <1)
return 0;
bool *accessible = new bool[rows*cols];
memset(accessible, 0, rows*cols);
int count = 0;
movingCountCore(threshold, accessible, rows, cols, 0, 0, count);
delete[] accessible;
return count;
}
void movingCountCore(int threshold, bool* accessMatrix,
int rows, int cols, int r, int c,
int& count)
{
if(checkAccessible(threshold, accessMatrix, rows, cols, r, c))
{
count+=1;
accessMatrix[r*cols+c] = true;
movingCountCore(threshold, accessMatrix, rows, cols, r+1, c, count);
movingCountCore(threshold, accessMatrix, rows, cols, r-1, c, count);
movingCountCore(threshold, accessMatrix, rows, cols, r, c+1, count);
movingCountCore(threshold, accessMatrix, rows, cols, r, c-1, count);
}
}
bool checkAccessible(int threshold, bool* accessMatrix,
int rows, int cols, int r, int c)
{
int number = sumOfIntNumber(r) + sumOfIntNumber(c);
if(r<rows && c<cols && r>-1 && c>-1 && accessMatrix[r*cols+c]==false
&& number<=threshold)
return true;
else
return false;
}
int sumOfIntNumber(int num)
{
int sum = 0;
while(num>0)
{
int tail = num%10;
num = num/10;
sum += tail;
}
return sum;
}
};