岛屿数量(广搜)
本文参考代码随想录
题目描述:
给定一个由 1(陆地)和 0(水)组成的矩阵,你需要计算岛屿的数量。岛屿由水平方向或垂直方向上相邻的陆地连接而成,并且四周都是水域。你可以假设矩阵外均被水包围。
输入描述:
第一行包含两个整数 N, M,表示矩阵的行数和列数。
后续 N 行,每行包含 M 个数字,数字为 1 或者 0。
输出描述:
输出一个整数,表示岛屿的数量。如果不存在岛屿,则输出 0。
输入示例:
4 5
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
输出示例:
3
提示信息
根据测试案例中所展示,岛屿数量共有 3 个,所以输出 3。
数据范围:
1 <= N, M <= 50
思路
易错点:只要 加入队列就代表 走过,就需要标记,而不是从队列拿出来的时候再去标记走过。
#include<bits/stdc++.h>
using namespace std;int directions[4][2] = {1,0,0,1,-1,0,0,-1};void bfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y){queue<pair<int, int>> que;que.push({x,y});visited[x][y] = 1;while(!que.empty()){pair<int, int> cur = que.front();que.pop();int curx = cur.first;int cury = cur.second;for(int i = 0; i < 4; i++){int nextx = curx + directions[i][0];int nexty = cury + directions[i][1];if(nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;if(!visited[nextx][nexty] && grid[nextx][nexty] == 1){que.push({nextx, nexty});visited[nextx][nexty] = true;}}}
}int main(){int m, n;cin >> n >> m;vector<vector<int>> grid(n, vector<int>(m, 0));for(int i = 0; i < n; i++){for(int j = 0; j < m; j++){cin >> grid[i][j];}}int result = 0;vector<vector<bool>> visited(n, vector<bool>(m, false));for(int i = 0; i < n; i++){for(int j = 0; j < m; j++){if(visited[i][j] == 0 && grid[i][j] == 1){result++;bfs(grid, visited, i, j);}}}cout << result;
}