力扣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
                }
            }
        }
    }
}
相关推荐
马可家的菠萝31 分钟前
Vue3 + Canvas 手绘笔记工程化实践:别把画布只当成一张 PNG
前端·vue.js·算法
watersink33 分钟前
机器学习极大似然估计与EM算法
人工智能·算法·机器学习
叠层归一研究院39 分钟前
如何用程序搭建一个 AGI 种子系统(一):从向量种子到无限生长引擎
人工智能·python·算法·机器学习·agi
科学实验家43 分钟前
并 查集
算法
AI服务老曹1 小时前
视觉算法模型管理性能优化指南:多版本平滑升级、灰度与快速回滚实战
算法·性能优化
l1258651 小时前
# RAG重排序实战:硅基流动bge-reranker-v2-m3在线API vs 本地CrossEncoder,一篇讲透两种方案
数据库·人工智能·python·深度学习·算法·机器学习·langchain
创世宇图2 小时前
【AI量化交易实战】第06讲:小雅再升级——Talib指标库与K线形态量化
算法
机器学习之心2 小时前
CPO-SVR:用冠豪猪优化算法给支持向量回归机“自动调参“,一次预测多个指标
算法·回归·cpo-svr
Super 含2 小时前
Android 启动优化(三):Perfetto 实战——启动时间到底花在哪里?
jvm·算法
wangjialelele3 小时前
动态规划DP经典题型总结(Java、C++):路径、子数组、子序列、背包问题详解
java·c++·算法·面试·动态规划·代理模式