机器人的运动范围
题目描述
m*n,机器人上下左右运行。但不能进入行+列之和大于k的格子。问机器人能到达多少个格子
int MovingCount(int threshold, int rows, int cols)
{
if(threshold <=0 || rows<=0 || cols<=0)
return 0;
bool visited = new bool[rows*cols];
for(int i=0; i<rows; i++)
{
for(int j=0;j<cols;j++)
{
visited[i][j] = 0;
}
}
int count = CountCore(threshold, rows,cols,0,0,visited);
return count;
}
int CountCore(int threshold, int rows, int cols, int row, int col, bool *visited)
{
int count = 0;
if(check(threshold, rows, cols, row, col, visited))
{
visited[row*cols + col] = true;
count = 1+ CountCore(threshold, rows,cols,row+1,col,visited) \
+CountCore(threshold, rows,cols,row-1,col,visited) \
+CountCore(threshold, rows,cols,row,col+1,visited) \
+CountCore(threshold, rows,cols,row,col-1,visited);
}
return count;
}
int getSum(int a, int b)
{
int sum=0;
int number[2] = {a, b};
for(int i=0; i<2; i++)
{
int n = number[i];
while(n!=0)
{
sum += n%10;
n = n/10;
}
}
return sum;
}
bool check(int threshold, int rows, int cols, int row, int col, bool *visited)
{
if(row >=0 && row<rows && col>=0 && col<cols &&!visited[row*cols + col]
&& getSum(row, col)<=threshold)
{
return true;
}
return false;
}