题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
看了讨论区 AC代码
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
int flag[100][100] = {0};
return move(0, 0, flag, rows, cols, threshold);
}
int move(int i, int j, int flag[][100],int rows, int cols, int threshold)
{
if (i < 0 || j < 0 || i >= rows || j >= cols
|| threshold < sum(i, j) || flag[i][j] == 1) {
return 0;
}
flag[i][j] = 1;
return move(i - 1, j, flag, rows, cols, threshold)
+ move(i + 1, j, flag, rows, cols, threshold)
+ move(i, j - 1, flag, rows, cols, threshold)
+ move(i, j + 1, flag, rows, cols, threshold)
+ 1;
}
int sum(int i, int j)
{
int sum = 0;
do{
sum += i % 10;
}while ((i /= 10) != 0);
do{
sum += j % 10;
}while ((j /= 10) != 0);
return sum;
}
};
改进代码
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
bool *flag = new bool[rows*cols]{false};
int cnt = move(0, 0, flag, rows, cols, threshold);
delete[] flag;
return cnt;
}
int move(int i, int j, bool* flag,int rows, int cols, int threshold)
{
if (i < 0 || j < 0 || i >= rows || j >= cols
|| threshold < sum(i, j) || *(flag + cols * i + j)) {
return 0;
}
*(flag + cols * i + j) = true;
return move(i - 1, j, flag, rows, cols, threshold)
+ move(i + 1, j, flag, rows, cols, threshold)
+ move(i, j - 1, flag, rows, cols, threshold)
+ move(i, j + 1, flag, rows, cols, threshold)
+ 1;
}
int sum(int i, int j)
{
int sum = 0;
do{
sum += i % 10;
}while ((i /= 10) != 0);
do{
sum += j % 10;
}while ((j /= 10) != 0);
return sum;
}
};
思路
DFS Deep First Search
BFS Breadth First Search
的拓展,
一个递归函数,向上下左右move
一个计算该点的位和是否大于预定值
存在的问题
int movingCount(int threshold, int rows, int cols)
{
int flag[rows][cols] = {0};
return move(0, 0, flag, threshold);
}
int move(int i, int j, int &flag[][], int threshold)
是数组定义与使用的问题,具体可见
具体可见 Problem 文集
网友评论