当前位置: 首页 > news >正文

18491 岛屿的数量

18491 岛屿的数量

⭐️难度:中等
🌟考点:搜索
📖
在这里插入图片描述

📚

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

🍎笔记
在这里插入图片描述

相关文章:

  • nn.BCELoss 介绍
  • 基于 Qt / HTTP/JSON 的智能天气预报系统测试报告
  • HCIA【NAT】
  • 机器学习和深度学习的关系
  • Cent OS7+Docker+Dify
  • 网络通信协议浅析:TCP/IP、UDP、HTTP 和 MQTT
  • 《Linux运维实战:Ubuntu 22.04修改root用户默认名并禁止登录》
  • Android Logcat总结
  • 最少刷题数
  • 端到端自动驾驶VLM模型:LMDrive: Closed-Loop End-to-End Driving with Large Language Models
  • 鸿蒙 ArkUI 权限配置说明
  • 【ArcGIS】ArcGIS10.6彻底卸载和ArcGIS10.2安装全过程
  • 内网穿透工具讲解
  • buu-jarvisoj_fm-好久不见52
  • Docker-MySQL安装-命令解读-常见命令-数据卷挂载-本地目录挂载-自定义镜像-网络-前端部署-DockerCompose
  • 最接近的三数之和
  • Xss复现
  • Elasticsearch 之 ElasticsearchRestTemplate 聚合查询
  • 2025年CNG 汽车加气站操作工题目分享
  • 用否定干掉无效流量:DeepBI如何精准提升亚马逊广告效果
  • 国家统计局:4月份各线城市商品住宅销售价格环比持平或略降
  • 大风+暴雨,中央气象台双预警齐发
  • 上海:到2027年,实现近海航线及重点海域5G网络高质量覆盖
  • 广西壮族自治区政府主席蓝天立任上被查
  • 竞彩湃|欧联杯决赛前,曼联、热刺继续划水?
  • 贵州仁怀通报“正新鸡排鸡腿里全是蛆”:已对同类产品封存送检