华为OD机试-宜居星球改造计划-BFS(JAVA 2025A卷)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

import java.util.*;
public class ChangeEarth {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<String[]> strings = new ArrayList<>();
        while(sc.hasNextLine()){
            String line = sc.nextLine();
            if(line.isEmpty()){
                break;
            }
            strings.add(line.split("\\s+"));
        }
        String[][] strings1= new String[strings.size()][];
        strings.toArray(strings1);
        solve(strings1);
    }

    private static void solve(String[][] strings) {
        for (int i = 0; i < strings.length; i++) {
            for (int j = 0; j < strings[0].length; j++) {
                if(strings[i][j].equals("NA")){
                    System.out.println("-1");
                    return;
                }
            }
        }
        LinkedList<int[]> queue = new LinkedList<>();
        int[][] directions = new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
        for (int i = 0; i < strings.length; i++) {
            for (int j = 0; j < strings[0].length; j++) {
                if(strings[i][j].equals("YES")){
                    queue.add(new int[]{i,j});
                }
            }
        }
        int res = 0;
        while(!queue.isEmpty()){
            boolean flag = false;
            int size = queue.size();
            for(int jj=0;jj<size;jj++){
                int[] poll = queue.poll();
                for(int i=0;i<4;i++){
                    int x = poll[0]+directions[i][0];
                    int y = poll[1]+directions[i][1];
                    if(x<0 || x>=strings.length || y<0 || y>=strings[0].length|| strings[x][y].equals("YES")){
                        continue;
                    }
                    if(strings[x][y].equals("NO")){
                        flag=true;
                        strings[x][y] = "YES";
                        queue.add(new int[]{x,y});
                    }
                }
            }
            if(flag){
                res++;
            }
        }
        System.out.println(res);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值