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

🍎笔记

相关推荐
Data_agent8 分钟前
Python 编程实战:函数与模块化编程及内置模块探索
开发语言·python
new_zhou8 分钟前
vs2019+qt工程中生成dump文件及调试
开发语言·qt·visual studio·dump调试
栈与堆33 分钟前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
一路向北·重庆分伦35 分钟前
03-01:MQ常见问题梳理
java·开发语言
一 乐36 分钟前
绿色农产品销售|基于springboot + vue绿色农产品销售系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·宠物
txinyu的博客39 分钟前
结合游戏场景理解,互斥锁,读写锁,自旋锁,CAS / 原子变量,分段锁
开发语言·c++·游戏
lhrimperial42 分钟前
企业智能知识库助手落地实践:从RAG到Multi-Agent
java·spring cloud·微服务·系统架构·知识图谱
YIN_尹1 小时前
【MySQL】数据类型(上)
android·mysql·adb
3***68841 小时前
Spring Boot中使用Server-Sent Events (SSE) 实现实时数据推送教程
java·spring boot·后端
阿里嘎多学长1 小时前
2026-01-11 GitHub 热点项目精选
开发语言·程序员·github·代码托管