本文最后更新于:2020年7月2日 晚上
问题描述:
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
实现如下:
class Solution
{
public:
void DFS(vector<vector<char> >& map, int row, int col, int x, int y)
{
if (x < 0 || y < 0 || x >= row || y >= col || map[x][y] == '0')
return;
map[x][y] = '0';
//向右
DFS(map, row, col, x, y + 1);
//向左
DFS(map, row, col, x, y - 1);
//向上
DFS(map, row, col, x - 1, y);
//向下
DFS(map, row, col, x + 1, y);
}
int islandsNumCount(vector<vector<char>>& map)
{
int row = map.size();
int col = map[0].size();
if (row == 0 || col == 0)
return 0;
int count = 0;
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
if (map[i][j] == '1')
{
//深度遍历
DFS(map, row, col, i, j);
++count;
}
}
}
return count;
}
};
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!