[leetcode]200. Number of Islands

来源:互联网 发布:linux查看实时日志命令 编辑:程序博客网 时间:2024/06/06 02:52

题目链接:https://leetcode.com/problems/number-of-islands/#/description

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



思路:每遇到一个1,开始向四个方向搜索,遇到后变为0,因为相邻的属于同一个islands;开始搜索下一个1。


class Solution{public:    int numIslands(vector<vector<char>>& grid)    {        g=grid;        int islands=0;        for(int i=0;i<g.size();i++)        {            for(int j=0;j<g[i].size();j++)            {                islands+=sink(i,j);            }        }        return islands;    }private:    vector<vector<char>> g;    int sink(int i,int j)    {        if(i<0 || i==g.size() || j<0 || j==g[i].size() || g[i][j]=='0')            return 0;        g[i][j]='0';        sink(i+1,j);        sink(i-1,j);        sink(i,j+1);        sink(i,j-1);        return 1;    }};


0 0