# Leetcode166: Number of Islands

141人阅读 评论(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:

11110110101100000000

Example 2:

11000110000010000011

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网站的观点或立场
个人资料
• 访问：74982次
• 积分：2408
• 等级：
• 排名：第17298名
• 原创：148篇
• 转载：119篇
• 译文：0篇
• 评论：6条
个人主页
文章分类
最新评论