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);
            }
        }
    }
}

🍎笔记

相关推荐
月亮邮递员6167 分钟前
Markdown语法总结
开发语言·前端·javascript
printfLILEI7 分钟前
php中的类与对象以及反序列化
linux·开发语言·php
曹牧8 分钟前
C#:主线程能够捕获到子线程中的异常
开发语言·数据库·c#
代码中介商9 分钟前
深入解析STL中的stack、queue与priority_queue
开发语言·c++
XS03010612 分钟前
Spring Bean 作用域 & 生命周期
java·后端·spring
NagatoYukee13 分钟前
Spring Security基础部分学习
java·学习·spring
彦为君13 分钟前
JavaSE-07-异常机制
java·开发语言·后端·python·spring
OxyTheCrack30 分钟前
【Golang】简述make与new内置函数以及两者的区别
开发语言·golang
Rain50940 分钟前
mini-cc 的 MCP 协议:给 AI 装个 USB-C 接口
c语言·开发语言·前端·人工智能·架构·node.js·ai编程
华科大胡子1 小时前
AI开发者的网络卡点:Anthropic连接超时
开发语言·php