这里写自定义目录标题
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
示例 2:
输入:m = 3, n = 1, k = 0
输出:1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int movingCount(int m, int n, int k) {
private int sum;
public int movingCount(int rows, int cols, int threshold) {
sum = 0;
boolean[] vis = new boolean[rows][cols];
solve(0,0,rows,cols,vis, threshold);
return sum;
}
private void solve(int x, int y, int rows, int cols, boolean[][] vis, int threshold) {
if(x<0||y<0||x>=rows||y>=cols||vis[x][y] || cul(x,y) > threshold) {
return;
}
vis[x][y] = true;
sum++;
solve(x+1, y, rows, cols, vis, threshold);
solve(x-1, y, rows, cols, vis, threshold);
solve(x, y+1, rows, cols, vis, threshold);
solve(x, y-1, rows, cols, vis, threshold);
}
private int cul(int x, int y) {
int res = 0;
while(x != 0) {
res += x % 10;
x /= 10;
}
while(y != 0){
res += y % 10;
y /= 10;
}
return res;
}
}
}
导入
如果你想加载一篇你写过的.md文件,在上方工具栏可以选择导入功能进行对应扩展名的文件导入,
继续你的创作。