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

🍎笔记

相关推荐
l1t29 分钟前
DeepSeek 4.1总结的Tom Lane 谈塑造 Postgres 三十年历程的架构决策
开发语言·数据库·postgresql·架构
欢迎来到祖安!1 小时前
企业微信 API 接口能力介绍:支持消息收发、图片发送、表情互动、联系人管理等多场景应用
java·前端·数据仓库·spring cloud·企业微信
dadaobusi5 小时前
学习:RV lkvm SBI
java·学习·spring
一笑的小酒馆6 小时前
Androidiot开发之猫脸识别
android
djarmy6 小时前
MAIN.c(1): warning C318: can’t open file ‘STC8G.H’ 报错 解决 分析
c语言·开发语言·mongodb
HEJOO97 小时前
深入理解 Java volatile 关键字:原理、用法与常见误区
java·开发语言·spring
曹牧7 小时前
Java:no content to map due to end of input
java·开发语言
阿维的博客日记7 小时前
Example 类全场景实战指南
java·mybatis
梦梦代码精7 小时前
《回收租赁系统技术选型避坑指南:业务闭环与二开自由度详解》
开发语言·低代码·docker·开源·代码规范
两点王爷7 小时前
SpringBoot 项目集成 GeoServer 源码,实现地图服务发布
java·spring boot·后端