美文网首页
LeetCode每日一题 之 机器人的运动范围

LeetCode每日一题 之 机器人的运动范围

作者: ZSACH | 来源:发表于2020-04-25 09:49 被阅读0次

题目:地上有一个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。请问该机器人能够到达多少个格子? 题目地址

解题思路

这道题需要我们考虑两个问题

怎么走

这明显是一个图的遍历问题,我们可以使用深度DFS和广度BFS。显然深度优先更适合这道题,我们可以使用回溯法借助深度优先,往深处遍历,发现不合适的点,回退一步,以回退点为起点,再向其他的方向深度优先遍历。

怎么判断已经走过

显然我们需要一个外部存储存储已经走的点,二维数组就很合适。坐标的题类型都可以二外数组判断是否重复。

代码

public class Solution {
 
    public int movingCount(int threshold, int rows, int cols) {
        //二外数组,记录是否已经走过
        int flag[][] = new int[rows][cols];
        return walk(0, 0, rows, cols, flag, threshold);
    }
 
    private int walk(int i, int j, int rows, int cols, int[][] flag, int threshold) {
        if (i < 0 || i >= rows || j < 0 || j >= cols || numSum(i) + numSum(j)  > threshold || flag[i][j] == 1) return 0;    
        flag[i][j] = 1;
        return walk(i - 1, j, rows, cols, flag, threshold)
            + walk(i + 1, j, rows, cols, flag, threshold)
            + walk(i, j - 1, rows, cols, flag, threshold)
            + walk(i, j + 1, rows, cols, flag, threshold)
            + 1;
    }
    
    private int numSum(int i) {
        int sum = 0;
        do{
            sum += i%10;
        }while((i = i/10) > 0);
        return sum;
    }
}

相关文章

网友评论

      本文标题:LeetCode每日一题 之 机器人的运动范围

      本文链接:https://www.haomeiwen.com/subject/xfshwhtx.html