博客
关于我
200. 岛屿的个数
阅读量:262 次
发布时间:2019-03-01

本文共 1593 字,大约阅读时间需要 5 分钟。

题目要求我们计算给定二维网格中的岛屿数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。网格的四个边均被水包围。

思路

为了高效地解决这个问题,我们可以使用深度优先搜索(DFS)算法。DFS 适合这种网格问题,因为它可以通过递归来访问所有相邻的点。

步骤如下:

  • 初始化一个访问状态的二维数组 visited,记录哪些点已经被访问过。
  • 遍历整个网格,对于每一个点,如果它是 '1' 且未被访问过,就开始进行 DFS。
  • 在 DFS 中,标记当前点为已访问,并递归访问它的上下左右四个相邻点。
  • 每次发现一个新的 '1' 且未被访问的点,就增加岛屿的计数。
  • 最后返回计数器的值,即为岛屿的数量。
  • 代码

    public class numIslands {    public int numIslands(char[][] grid) {        if (grid.length == 0) {            return 0;        }        int row = grid.length;        int col = grid[0].length;        boolean[][] visited = new boolean[row][col];        int count = 0;                for (int i = 0; i < row; i++) {            for (int j = 0; j < col; j++) {                if (grid[i][j] == '1' && !visited[i][j]) {                    count++;                    dfs(grid, visited, row, col, i, j);                }            }        }        return count;    }        private void dfs(char[][] grid, boolean[][] visited, int row, int col, int i, int j) {        if (i < 0 || j < 0 || i >= row || j >= col) {            return;        }        if (grid[i][j] == '0') {            return;        }        if (visited[i][j]) {            return;        }        visited[i][j] = true;        dfs(grid, visited, row, col, i - 1, j);        dfs(grid, visited, row, col, i + 1, j);        dfs(grid, visited, row, col, i, j - 1);        dfs(grid, visited, row, col, i, j + 1);    }}

    代码解释

    • numIslands 函数首先检查网格是否为空,如果为空,直接返回0。
    • 它初始化访问数组 visited 和计数器 count
    • 遍历每个点,如果发现未被访问的 '1',就调用 dfs 函数进行深度优先搜索。
    • dfs 函数检查当前点是否越界、是否是水或者是否已被访问,如果是,则标记为已访问,并递归访问相邻的四个方向。
    • 每次找到一个新的岛屿,计数器 count 加1。
    • 最后返回计数器的值,即为岛屿的数量。

    转载地址:http://mpwa.baihongyu.com/

    你可能感兴趣的文章
    MySQL8,体验不一样的安装方式!
    查看>>
    MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
    查看>>
    Mysql: 对换(替换)两条记录的同一个字段值
    查看>>
    mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
    查看>>
    MYSQL:基础——3N范式的表结构设计
    查看>>
    MYSQL:基础——触发器
    查看>>
    Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
    查看>>
    mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
    查看>>
    mysqldump 参数--lock-tables浅析
    查看>>
    mysqldump 导出中文乱码
    查看>>
    mysqldump 导出数据库中每张表的前n条
    查看>>
    mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
    查看>>
    Mysqldump参数大全(参数来源于mysql5.5.19源码)
    查看>>
    mysqldump备份时忽略某些表
    查看>>
    mysqldump实现数据备份及灾难恢复
    查看>>
    mysqldump数据库备份无法进行操作只能查询 --single-transaction
    查看>>
    mysqldump的一些用法
    查看>>
    mysqli
    查看>>
    MySQLIntegrityConstraintViolationException异常处理
    查看>>
    mysqlreport分析工具详解
    查看>>