力扣200. 岛屿数量(BFS)

Problem: 200. 岛屿数量

文章目录

题目描述

思路及解法

1.定义方向数组:定义一个方向数组 DIRECTIONS,表示上、下、左、右四个方向的移动。

2.获取网格的行数和列数同时初始化一个计数器 numIslands 用于记录岛屿的数量。

3.使用两层循环遍历整个网格,如果遇到一个未访问的陆地 '1',计数器 numIslands 增加1,并调用 BFS 方法来标记整个岛屿。

4.BFS方法:

4.1.创建一个队列 queue,并将当前陆地的位置加入队列。

4.2.将当前陆地标记为已访问,即将 gridrowcol 设置为 '0'。

4.3.使用一个循环处理队列中的每个位置,遍历四个遍历四个方向,根据方向数组计算新位置。如果新位置是有效的且为未访问的陆地 '1',将其加入队列并标记为已访问。

复杂度

时间复杂度:

O ( M × N ) O(M \times N) O(M×N);其中 M M M和 N N N分别为举证grid的行数与列数

空间复杂度:

O ( M × N ) O(M \times N) O(M×N)

Code

java 复制代码
class Solution {
   // Define four directions: up, down, left, and right
    private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    /**
     * Number of Islands
     *
     * @param grid Given array
     * @return int
     */
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }

        int rows = grid.length;
        int cols = grid[0].length;
        int numIslands = 0;

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (grid[row][col] == '1') {
                    numIslands++;
                    bfs(grid, row, col);
                }
            }
        }

        return numIslands;
    }

    /**
     * @param grid Given array
     * @param row  The row of array
     * @param col  The column of array
     */
    private void bfs(char[][] grid, int row, int col) {
        int rows = grid.length;
        int cols = grid[0].length;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{row, col});
        grid[row][col] = '0';  // Mark as accessed

        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int currentRow = current[0];
            int currentCol = current[1];

            for (int[] direction : DIRECTIONS) {
                int newRow = currentRow + direction[0];
                int newCol = currentCol + direction[1];

                if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && grid[newRow][newCol] == '1') {
                    queue.offer(new int[]{newRow, newCol});
                    grid[newRow][newCol] = '0';  // Mark as accessed
                }
            }
        }
    }
}
相关推荐
洛水水7 分钟前
【力扣100题】76.搜索插入位置
数据结构·算法·leetcode
Techblog of HaoWANG11 分钟前
智巡守卫:多模态巡检智能体算法服务端设计与实现——基于Ollama+Qwen3.5的自动化巡检报告生成系统
运维·人工智能·算法·目标检测·自动化·边缘计算
小蒋学算法21 分钟前
算法-灌溉花园的最少龙头数目-贪心
算法
满怀冰雪22 分钟前
第07篇-差分算法-高效处理区间修改问题
数据结构·算法
KaMeidebaby24 分钟前
卡梅德生物技术快报|重组蛋白的表达和纯化:工艺调试全记录:大肠杆菌体系重组蛋白的表达和纯化参数标定(肠激酶轻链案例)
前端·人工智能·算法·数据挖掘·数据分析
ZPC821040 分钟前
如何将机械臂末端定位精度提升至微米如何进行标定
人工智能·算法·机器人
wabs66641 分钟前
关于动态规划【力扣343.整数拆分的递推公式怎么理解?】
算法·leetcode·动态规划
测试狗科研平台42 分钟前
第一性原理CO2还原反应计算流程和软件推荐
科技·算法·云计算
SEO_juper42 分钟前
2026 谷歌 SEO&GEO 常见问题合集:收录、排名、内容、技术全解析
算法·谷歌·常见问题·seo·跨境电商·外贸·geo
叫我:松哥1 小时前
基于卷积神经网络的静态手势语识别算法,在测试集上的识别准确率达到97.5%
人工智能·python·深度学习·神经网络·算法·cnn