646人阅读 评论(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.

# AC代码

class Solution {
public:
//等价于计算连通子图的个数
int numIslands(vector<vector<char>>& grid) {
if (grid.empty())
return 0;

//计算该二维数组的行列
int rows = grid.size();
int cols = grid[0].size();

int count = 0;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
if (grid[i][j] == '1')
{
++count;
dfs(grid, i, j);
}
continue;
}//for
}//for
return count;
}

void dfs(vector<vector<char>> &grid, int r, int c)
{
if (grid.empty())
return;

//计算该二维数组的行列
int rows = grid.size();
int cols = grid[0].size();

if (r < 0 || r >= rows || c < 0 || c >= cols)
return;

if (grid[r][c] == '1')
{
//改变当前元素值为非'1'
grid[r][c] = '2';
dfs(grid, r, c + 1);
dfs(grid, r + 1, c);
dfs(grid, r, c - 1);
dfs(grid, r - 1, c);
}//if
return;
}
};

GitHub测试程序源码

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：681491次
• 积分：10009
• 等级：
• 排名：第1787名
• 原创：392篇
• 转载：49篇
• 译文：0篇
• 评论：177条
博客专栏
 LeetCode & LintCode 题解 文章：215篇 阅读：172874
 Python3爬虫之路 文章：10篇 阅读：86983
评论排行
最新评论