版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/85564666
地上有一个m行和n列的方格。
一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于k 的格子。
请问该机器人能够达到多少个格子?
样例1
输入:k=7, m=4, n=5
输出:20
样例2
输入:k=18, m=40, n=40
输出:1484
解释:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
但是,它不能进入方格(35,38),因为3+5+3+8 = 19。
注意:
- 0<=m<=50
- 0<=n<=50
- 0<=k<=100
dfs入门题啊
class Solution {
public:
int ans = 0;
bool check(int k, int x, int y){
int t = 0;
while(x){
t += x % 10;
x /= 10;
}
while(y){
t += y % 10;
y /= 10;
}
return t <= k ? true : false;
}
void dfs(int threshold, int rows, int cols, int x, int y, vector<vector<bool>>& visited){
int Next[4][2] = {0,1,0,-1,1,0,-1,0};
for(int k = 0; k < 4; k ++){
int nx = x + Next[k][0];
int ny = y + Next[k][1];
if(nx>=0 && ny>=0 && nx < rows && ny < cols && !visited[nx][ny] && check(threshold, nx, ny)){
visited[nx][ny] = true;
ans ++;
dfs(threshold, rows, cols, nx, ny, visited);
}
}
}
int movingCount(int threshold, int rows, int cols)
{
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
if(threshold < 1) return 1;
if(!rows || ! cols) return rows + cols;
visited[0][0] = true;
ans ++;
dfs(threshold, rows, cols, 0, 0, visited);
return ans;
}
};