java图的遍历-机器人的活动范围

机器人的运动范围

http://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8

题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
示例1
输入
5,10,10
返回值
21

解题纪要-参考官方题解

该题不会做,需要复习。需要实现图的深度遍历和广度遍历

Java代码实现-具体见注释

//图的深度遍历
/*public class Solution1 {
    int[] dir=new int[]{-1,0,1,0,-1};//左上右下的顺序走
    int ans=0;

    public int movingCount(int threshold, int rows, int cols)
    {
        if(threshold <= 0) return 0;
        int[][] mark=new int[rows][cols];
        dfs(0,0,threshold,rows,cols,mark);
        return ans;
    }
    public int check(int x){
        int sum = 0;
        while(x > 0){
            sum += x % 10;
            x /= 10;
        }
        return sum;
    }
    public void dfs(int x,int y,int sho,int r,int c,int[][] mark){
        if(x < 0 || x >= r || y < 0 || y >= c || mark[x][y]==1) return;
        if(check(x)+check(y) > sho) return;
        mark[x][y]=1;
        ans += 1;
        for(int i = 0;i < 4;i++){
            dfs(x + dir[i],y + dir[i + 1],sho,r,c,mark);
        }
    }
}*/
//图的广度遍历
import java.util.*;
public class Solution{
    int[] dir=new int[]{-1,0,1,0,-1};//左上右下的顺序走
    public int check(int x){
        int sum = 0;
        while(x > 0){
            sum += x % 10;
            x /= 10;
        }
        return sum;
    }
    public int movingCount(int threshold, int rows, int cols)
    {
        if(threshold <= 0) return 0;
        //新建一个二维数组标记走过的路
        boolean[][] mark = new boolean[rows][cols];
        //创建一个变量保存走过的格子树
        int res = 0;
        //建一个队列,里面存储一个4个元素的数组
        //[0,0] 行和列的值
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{0,0});
        mark[0][0]=true;
        //将可能符合的坐标放入队列中,当队列为空时退出循环
        while(!queue.isEmpty()){
            int[] tem = queue.poll();
            res++;
            for(int i=0;i<4;i++){
                int x=tem[0]+dir[i],y=tem[1]+dir[i+1];
                if(x >= 0 && x < rows && y >= 0 && y < cols && mark[x][y] == false){
                    if(check(x)+ check(y) <= threshold){
                        queue.add(new int[]{x,y});
                        mark[x][y] = true;
                    }
                }
            }
        }
        return res;
    }
}
Leetcode-牛客-刷题笔记 文章被收录于专栏

本专栏主要用于分享栏主在准备java后端面试过程中的刷题笔记

全部评论

相关推荐

26应届求职ing:你这是报了豆音四哥的班?双非本硕拿这两个项目写简历里投100多家嵌软也没什么面试,感觉项目简单了,很多人用
点赞 评论 收藏
分享
影04714:把图书管理系统那个项目经验内容适当的减少掉,然后改成据为己有不要说团队项目,因为图书管理系统这类常见的谁来了都能独立写出来,提问能圆过来即可
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务