LeetCode: 200. Number of Islands

LeetCode: 200. Number of Islands

题目描述

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

解题思路

依次遍历每一个格子,如果该格子是 1,则深度优先搜索将和它相连的为 1 的格子都标记为 0

AC 代码

class Solution 
{
    void dfsWithFlag(vector<vector<char>>& grid, int i, int j)
    {
        if(i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size() || grid[i][j] == '0')
        {
            return ;
        }
        else
        {
            grid[i][j] = '0';
        }

        const static int dirs[][2] = 
            {
                {0,  1}, // 下
                {0, -1}, // 上
                {1,  0}, // 右
                {-1, 0}, // 左
            };

        for(int k = 0; k < 4; ++k)
        {
            int tx = i + dirs[k][0];
            int ty = j + dirs[k][1];

            dfsWithFlag(grid, tx, ty);
        }
    }
public:
    int numIslands(vector<vector<char>>& grid) 
    {
        int cnt = 0;

        for(int i = 0; i < grid.size(); ++i)
        {
            for(int j = 0; j < grid[i].size(); ++j)
            {
                if(grid[i][j] == '1')
                {
                    ++cnt;
                    dfsWithFlag(grid, i, j);
                }
            }
        }

        return cnt;
    }
};
全部评论

相关推荐

兄弟们,绩效自评一定得给自己打A啊!千万别谦虚给低分,不然领导正愁给谁高分,你这不就“主动请缨”了嘛,而且多数领导不会给你更高分。我几年前试用期绩效自评打了B,领导就给了同等级,还好是试用期。真别等领导主动给高评价!
准备进厂的劳伦斯很迷人:小学时候有个册子 自评 小组 老师 我谦虚打了个b 小组别人给我打b 老师来句我觉得能给他打a 但是小组长说他自评是b怎么能打高呢 那时候我才明白的道理
点赞 评论 收藏
分享
程序员鼠鼠_春招版:都很烂大街,rpc也基本没人问,考研吧,不然就包装一段实习再去
点赞 评论 收藏
分享
02-05 08:49
已编辑
武汉大学 Web前端
野猪不是猪🐗:36k和36k之间亦有差距,ms的36k和pdd的36k不是一个概念
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务