队列例题-连通块

代码如下:

  1 #include <iostream>
  2 using namespace std;
  3 struct Node
  4 {
  5     int x,y;
  6 };
  7 int a[100][100],h,w;
  8 //队列
  9 struct Queue
 10 {
 11     Node a[100];
 12     int front;
 13     int rear;
 14 } q;
 15 int n=50;//存实际占用空间为n+1,即0-n。
 16 //队满
 17 bool isfull()
 18 {
 19     return (q.rear+1)%(n+1)==q.front;
 20 }
 21 //队空
 22 bool isempty()
 23 {
 24     return q.rear==q.front;
 25 }
 26 //入队
 27 void inq(Node x)
 28 {
 29     if(!isfull())
 30     {
 31         q.a[q.rear]=x;
 32         q.rear= (q.rear+1)%(n+1);
 33     }
 34     else
 35     {
 36         cout<<"The queue is full.";
 37     }
 38 }
 39 //出队
 40 Node outq()
 41 {
 42     Node t;
 43     t=q.a[q.front];
 44     q.front=(q.front+1)%(n+1);
 45     return t;
 46 
 47 }
 48 void mark(Node t_n)
 49 {
 50     Node t;
 51     a[t_n.x][t_n.y]=2;
 52     if(t_n.x-1>=0)
 53     {
 54         t.x=t_n.x-1;
 55         t.y=t_n.y;
 56         if(a[t.x][t.y]==1)
 57         {
 58             inq(t);
 59         }
 60     }
 61     if(t_n.y-1>=0)
 62     {
 63         t.x=t_n.x;
 64         t.y=t_n.y-1;
 65         if(a[t.x][t.y]==1)
 66         {
 67             inq(t);
 68         }
 69     }
 70     if(t_n.x+1<w)
 71     {
 72         t.x=t_n.x+1;
 73         t.y=t_n.y;
 74         if(a[t.x][t.y]==1)
 75         {
 76             inq(t);
 77         }
 78     }
 79     if(t_n.y+1<h)
 80     {
 81         t.x=t_n.x;
 82         t.y=t_n.y+1;
 83         if(a[t.x][t.y]==1)
 84         {
 85             inq(t);
 86         }
 87     }
 88     while(!isempty())
 89     {
 90         mark(outq());
 91     }
 92 }
 93 main()
 94 {
 95     q.front=0;
 96     q.rear=0;
 97     int c=0;
 98     cin>>h>>w;
 99     for(int i=0; i<h; i++)
100     {
101         for(int j=0; j<w; j++)
102         {
103             cin>>a[i][j];
104         }
105     }
106     for(int i=0; i<h; i++)
107     {
108         for(int j=0; j<w; j++)
109         {
110             if(a[i][j]==1)
111             {
112                 Node t;
113                 t.x=i;
114                 t.y=j;
115                 mark(t);
116                 c++;
117             }
118         }
119     }
120     cout<<c;
121 }

运行效果1:

运行效果2:

转载于:https://www.cnblogs.com/wanjinliu/p/11415784.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值