超详细注解版

机器人的运动范围

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

import java.util.*;
public class Solution {
    public int movingCount(int threshold, int rows, int cols)
    {
        //新建一个二维数组标记走过的路
        boolean[][] visited = new boolean[rows][cols];
        //创建一个变量保存走过的格子树
        int res = 0;
        //建一个队列,里面存储一个4个元素的数组 
        //[0,0,0,0] 前两个是行和列的值,后两位是行和列的位数和
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{0,0,0,0});
        //将可能符合的坐标放入队列中,当队列为空时退出循环
        while(!queue.isEmpty()){
            int[] tem = queue.poll();
            //分别创建变量存储坐标和位数和
            int y=tem[0],x=tem[1],s1=tem[2],s2=tem[3];
            //判断当走到边界、位数和大于目标数、或者已经走过的格子时,直接跳过
            if(y>=rows||x>=cols||threshold<s1+s2||visited[y][x]) continue;
            res++;
            visited[y][x] = true;
            //将能到达的格子添加到队列中
            //当坐标由  9->10,位数和变化为9->1,相差8
            //当坐标由  19->20,位数和变化为10->2,相差8
            queue.add(new int[]{y+1,x,(y+1)%10!=0?s1+1:s1-8,s2});
            queue.add(new int[]{y,x+1,s1,(x+1)%10!=0?s2+1:s2-8});
        }
        return res;
    }
}
全部评论

相关推荐

10-21 00:37
已编辑
门头沟学院 C++
小浪_Coding:你问别人,本来就是有求于人,别人肯定没有义务免费回答你丫, 有点流量每天私信可能都十几,几十条的,大家都有工作和自己的事情, 付费也是正常的, 就像你请别人搭把手, 总得给人家买瓶水喝吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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