索引请参考:系列目录
题目:
- 地上有一个m行n列的方格。一个机器人从坐标(0,0)的各自开始移动,它每次可以向左右上下移动一个各自,但不能进入行坐标和列坐标数位之和大于k的格子。
- 示例:
- k = 18,机器人能够进入(35,37)原因是:3+5+3+7 = 18,但是它不能进入方格(35,38),因为3+5+3+8 = 19.
分析:
思路:
- 本题的主要思路时深度优先搜索,当然广度优先搜索也可以
给出一个6*20的矩阵,k = 9
- (1)将矩阵中的所有元素初始化为0,如果机器人已经进入该方格,则该方格变为1,
- (2)开始进行遍历。直到遍历到(0,9)、(1,8)、(2,7)、(3,6)、(4,5)、(5,4)
- (3)当下一次遍历时,由于(2,8)、(3,7)、(4,6)、(5,5)不满足条件,所以结果为:
- (3)再一次遍历
- (4)不断遍历直至最后结果为
所以,最终机器人走过78个格子
代码:
int result(int n){
int sum = 0;
while(n)
{
sum += (n % 10);
n /= 10;
}
return sum;
}
void dfs(vector<vector<int>> & arr,vector<vector<bool>> & visited,const int threshold,const int x,const int y,int & ret){
visited[y][x] = true;
int height = arr.size();
int width = arr[0].size();
//上
if(y - 1 >= 0 && visited[y - 1][x] == false)
if(result(y - 1) + result(x) <= threshold)
dfs(arr,visited,threshold,x,y - 1,++ret);
//下
if(y + 1 < height && visited[y + 1][x] == false)
if(result(y + 1) + result(x) <= threshold)
dfs(arr,visited,threshold,x,y + 1,++ret);
//左
if(x - 1 >= 0 && visited[y][x - 1] == false)
if(result(y) + result(x - 1) <= threshold)
dfs(arr,visited,threshold,x - 1,y,++ret);
//右
if(x + 1 < width && visited[y][x + 1] == false)
if(result(y) + result(x + 1) <= threshold)
dfs(arr,visited,threshold,x + 1,y,++ret);
}
int movingCount(int threshold, int rows, int cols)
{
vector<vector<int>> arr(cols,vector<int>(rows,-1));
vector<vector<bool>>visited(cols,vector<bool>(rows,false));
int ret = 0;
if(threshold >= 0)
dfs(arr, visited, threshold, 0, 0,++ret);
return ret;
}
牛客运行结果: