题目
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.
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
解法一
思路:逐元素遍历输入的二维数组,遇到1时展开BFS搜索,并用记录下遇到过的节点。
参考资料:https://www.cnblogs.com/grandyang/p/4402656.html
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) {
return 0;
}
int n_row = grid.size();
int n_col = grid[0].size();
int res = 0;
vector<vector<bool>> visited(n_row, vector<bool>(n_col));
vector<int> dirX{-1, 0, 1, 0}, dirY{0, 1, 0, -1};
for (int i = 0; i < n_row; i++) {
for (int j = 0; j < n_col; j++) {
if (grid[i][j] == '0' || visited[i][j])
continue;
++res;
queue<int> q{{i * n_col + j}};
while (!q.empty()) {
int t = q.front(); q.pop();
for (int k = 0; k < 4; k++) {
int x = t / n_col + dirX[k];
int y = t % n_col + dirY[k];
if (x < 0 || x >= n_row || y < 0 || y >= n_col || grid[x][y] == '0' || visited[x][y])
continue;
visited[x][y] = true;
q.push(x * n_col + y);
}
}
}
}
return res;
}
};
内容来源于网络如有侵权请私信删除
- 还没有人评论,欢迎说说您的想法!