题解 | 机器人的运动范围

机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8

import java.util.*;
public class Solution {
    public int movingCount(int threshold, int rows, int cols) {
        Queue<int[]> que = new LinkedList<>();
        int count = 0;

        boolean[][] used = new boolean[rows][cols];

        que.offer(new int []{0,0});
        used[0][0] = true;

        while(!que.isEmpty()){
            int[] p = que.poll();
            count++;

            int x = p[0];
            int y = p[1];

            if(x+1<rows && !used[x+1][y]){
                int sum1 = computeSum(x+1,y);
                used[x+1][y] = true;
                if(sum1<=threshold) que.offer(new int[]{x+1,y});
            }

            if(y+1<cols && !used[x][y+1]){
                int sum3 = computeSum(x,y+1);
                used[x][y+1]= true;
                if(sum3<=threshold) que.offer(new int[]{x,y+1});
            }   
        }

        return count; 
    }

    public int computeSum(int x, int y){
        int sum = 0;
        while(x!=0){
            sum+=x%10;
            x = x/10;
        }

        while(y!=0){
            sum+=y%10;
            y=y/10;
        }

        return sum;
    }

    
}

全部评论

相关推荐

05-16 09:20
已编辑
中国民航大学 Java
点赞 评论 收藏
分享
真烦好烦真烦:牛友太有实力了
点赞 评论 收藏
分享
秋盈丶:后续:我在宿舍群里和大学同学分享了这事儿,我好兄弟气不过把他挂到某脉上了,10w+阅读量几百条评论,直接干成精品贴子,爽
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务