【leetcode】 200. Number of Islands

本文介绍了一种使用深度优先搜索(DFS)算法解决岛屿数量问题的方法。通过递归地访问地图上的每个单元格,将相连的陆地标记并计数,最终得出不相连陆地块的数量。此算法的时间复杂度为O(n^2),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的dfs递归,我们把每个访问到的‘1’,都对其进行dfs,使得与他相邻的‘1’都置为‘0’

/**
 * @author          johnsondu
 * @problem         Number of Islands
 * @url             https://leetcode.com/problems/number-of-islands/
 * @timeComlexity   O(n^2)
 * @spaceComplexity O(1)
 * @strategy        See code.
 */
 
 int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
class Solution {
public:
    void dfs(int x, int y, int row, int col, vector<vector<char>>& grid)
    {
        for(int i = 0; i < 4; i ++) {
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(tx < row && tx >= 0 && ty < col && ty >= 0) {
                if(grid[tx][ty] == '1') {
                    grid[tx][ty] = '0';
                    dfs(tx, ty, row, col, grid);
                }
            }
        }
    }

    int numIslands(vector<vector<char>>& grid) {
        int row = grid.size();
        if(row == 0) return 0;
        int col = grid[0].size();
        if(col == 0) return 0;
        
        int cnt = 0;
        for(int i = 0; i < row; i ++)
            for(int j = 0; j < col; j ++) {
                if(grid[i][j] == '1') {
                    cnt ++;
                    dfs(i, j, row, col, grid);
                }
            }
        return cnt;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值