题目描述,给出一个由01组成的矩阵,任何连在一起的1都看作一块岛,问矩阵中有几个岛

先默写一下BFS的模版

  1. void BFS(int x){
  2. queue<int> q;
  3. q.push(x);
  4. while(!q.empty()){
  5. int top = q.front;
  6. q.pop();
  7. //下一层符合条件的结点入队,并标记已经入队
  8. }
  9. }

代码

  1. #include<algorithm>
  2. #include<queue>
  3. #include<cstdio>
  4. using namespace std;
  5. const int maxn = 10010;
  6. struct Node{
  7. int x, y;
  8. }node[maxn];
  9. int n, m, ans = 0;
  10. int matrix[maxn][maxn];
  11. bool inq[maxn][maxn] = {false};
  12. int X[4] = {0, 0, 1, -1};
  13. int Y[4] = {1, -1, 0, 0};
  14. bool judge(int x, int y){
  15. if(x >= n || y >= m || x < 0 || y < 0 || inq[x][y] == true || matrix[x][y] == 0){
  16. return false;
  17. }
  18. else {
  19. return true;
  20. }
  21. }
  22. void BFS(int x, int y){//这道题里的BFS的作用是找出给定节点所在的岛
  23. queue<Node> q;
  24. Node temp;
  25. temp.x = x, temp.y = y;
  26. q.push(temp);
  27. inq[x][y] = true;
  28. while(!q.empty()){
  29. Node top = q.front();
  30. q.pop();
  31. for(int i = 0; i < 4; i++){
  32. int newx = top.x + X[i];
  33. int newy = top.y + Y[i];
  34. if(judge(newx, newy)){
  35. inq[newx][newy] = true;
  36. temp.x = newx, temp.y = newy;
  37. q.push(temp);
  38. }
  39. }
  40. }
  41. }
  42. int main(){
  43. scanf("%d%d",&n,&m);
  44. for(int i = 0; i < n; i++){
  45. for(int j = 0; j < m; j++){
  46. scanf("%d",&matrix[i][j]);
  47. }
  48. }
  49. for(int i = 0; i < n; i++){
  50. for(int j = 0; j < m; j++){
  51. if(inq[i][j]==false && matrix[i][j] == 1){
  52. BFS(i, j);
  53. ans++;
  54. }
  55. }
  56. }
  57. printf("%d",ans);
  58. }