18491 岛屿的数量

18491 岛屿的数量

⭐️难度:中等

🌟考点:搜索

📖

📚

java 复制代码
import java.util.*;

public class Main {
    static int[][] a = new int[505][505];
    static int[] dx = {0,0,1,-1};
    static int n;
    static int[] dy = {1,-1,0,0};  // 用数组表示移动方向,分别对应 右 左 上 下

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                a[i][j] = sc.nextInt();
            }
        }

        int ans = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                if(a[i][j] == 1){
                    bfs(i,j);
                    ans ++;
                }
            }
        }
        System.out.println(ans);
    }

    static void bfs(int x,int y){
        a[x][y] = 0; // 访问过的陆地变成海洋
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                int ax = dx[i] + x;
                int ay = dy[i] + y;
                if(ax < 1 || ay < 1 || ax > n + 1 || ay > n + 1 || a[ax][ay] == 0) continue; // 检查坐标合法,且是陆地
                bfs(ax,ay);
            }
        }
    }
}

🍎笔记

相关推荐
奔跑吧 android22 分钟前
【android bluetooth 协议分析 18】【PBAP详解 2】【车机为何不显示电话号码为空的联系人信息】
android·蓝牙电话·hfp·pbap·电话簿
深盾科技22 分钟前
安卓二次打包技术深度拆解:从逆向篡改到防护逻辑
android
4Forsee23 分钟前
【Android】消息机制
android·java·前端
骚戴31 分钟前
PDF或Word转图片(多线程+aspose+函数式接口)
java·开发语言
姓蔡小朋友34 分钟前
SpringDataRedis
java·开发语言·redis
CodeCraft Studio36 分钟前
国产化Excel处理控件Spire.XLS教程:如何使用 Java 将 TXT 文本转换为 Excel 表格
java·word·excel·spire·文档格式转换·txt转excel
Predestination王瀞潞42 分钟前
Python3:Eighth 函数
开发语言·python
朝新_1 小时前
【SpringBoot】玩转 Spring Boot 日志:级别划分、持久化、格式配置及 Lombok 简化使用
java·spring boot·笔记·后端·spring·javaee
m0_748248021 小时前
Spring设计模式刨根问底
java·spring·设计模式
喝杯牛奶丶1 小时前
MySQL隔离级别:大厂为何偏爱RC?
java·数据库·mysql·面试