ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

队列例题-连通块

2019-08-26 23:53:57  阅读:250  来源: 互联网

标签:Node 连通 队列 inq int front 100 例题 rear


代码如下:

  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:

标签:Node,连通,队列,inq,int,front,100,例题,rear
来源: https://www.cnblogs.com/wanjinliu/p/11415784.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有