200. Number of Islands

来源:互联网 发布:linux 机器重启日志 编辑:程序博客网 时间:2024/05/17 06:04

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
class Solution {public:void help(int x,int y,vector<vector<char>>&grid){    if(x<0||x>=grid.size()||y<0||y>=grid[x].size()||grid[x][y]!='1')    return;    grid[x][y]='0';    help(x+1,y,grid);    help(x-1,y,grid);    help(x,y+1,grid);    help(x,y-1,grid);    }    int numIslands(vector<vector<char>>& grid) {        int answer=0;        for(int i=0;i<grid.size();i++)        for(int j=0;j<grid[i].size();j++)        {            if(grid[i][j]=='1')            {                help(i,j,grid);                ++answer;            }        }        return answer;            }};


0 0
原创粉丝点击