关闭

Leetcode166: Number of Islands

标签: leetcodealgorithm
114人阅读 评论(0) 收藏 举报
分类:

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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

用dfs搜索,遇到1则把它周围的1全部变成非1,然后计算1的数目。

class Solution {
public:
    void dfs(int i, int j, vector<vector<char>>& grid)
    {
        if(i>=0 && i < grid.size() && j >= 0 && j < grid[0].size())
        {
            if(grid[i][j] == '1')
            {
                grid[i][j] = '2';
                dfs(i-1,j,grid);
                dfs(i+1,j,grid);
                dfs(i,j-1,grid);
                dfs(i,j+1,grid);
            }
        }
    }
    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size();
        if(m==0)
            return 0;
        int n = grid[0].size();
        if(n==0)
            return 0;
        int res = 0;
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(grid[i][j] == '1')
                {
                    res++;
                    dfs(i,j,grid);
                }
            }
        }
        return res;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:60711次
    • 积分:2266
    • 等级:
    • 排名:第16641名
    • 原创:148篇
    • 转载:119篇
    • 译文:0篇
    • 评论:3条
    个人主页
    文章分类
    最新评论