前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0200 - Number of Islands

LeetCode 0200 - Number of Islands

作者头像
Reck Zhang
发布2021-08-11 14:56:18
3250
发布2021-08-11 14:56:18
举报
文章被收录于专栏:Reck ZhangReck ZhangReck Zhang

Number of Islands

Desicription

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

Solution

class Solution {
private:
    int n;
    int m;
    int dir[4][2] = {1, 0, -1, 0, 0, -1, 0, 1};
    void dfs(int x, int y, vector<vector<char>>& grid) {
        if(grid[x][y] == '1')
            grid[x][y] = '0';
        for(int i = 0; i < 4; i++) {
            int dx = x + dir[i][0];
            int dy = y + dir[i][1];
            if(dx < 0 || dx == n || dy < 0 || dy >= m || grid[dx][dy] == '0')
                continue;
            dfs(dx, dy, grid);
        }
    }
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.size() == 0)
            return 0;
        n = grid.size();
        m = grid[0].size();
        int res = 0;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == '1') {
                    res++;
                    dfs(i, j, grid);
                }
            }
        }
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Number of Islands
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档