您的位置:首页 > 其它

图之 宽度优先遍历 BFS 邻接表创建的图

2016-09-22 22:32 369 查看

BFS 邻接表创建

#include<stdio.h>
#include<iostream>
using namespace std;

#define MaxSize 100
typedef int VertexType;
typedef int EdgeType;

typedef struct ArcNode
{
int adjvex;
struct ArcNode *nextarc;
int info;
}ArcNode;

typedef struct VNode
{
VertexType data;
ArcNode *firstarc;
}VNode;

typedef struct
{
VNode adjlist[MaxSize];
int n, e;
}AGraph;

void CreateDG(AGraph &G)
{
int i, k, v1, v2;
cin >> G.n;  //顶点数目
cin >> G.e;  //边数目
for (i = 1; i <= G.n; ++i)  //from 1...n  为了下标与序号相对应
{
G.adjlist[i].data = i;   //给顶点赋值
G.adjlist[i].firstarc = NULL;
}
for (k = 0; k < G.e; ++k)
{
cin >> v1 >> v2;   //
ArcNode *p;
p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = v2;
p->nextarc = G.adjlist[v1].firstarc;    // 链表用头插法建立
G.adjlist[v1].firstarc = p;
}
}

void BFSTraverse(AGraph G)
{
ArcNode *p;
int visited[MaxSize];
int i, j;
int que[MaxSize];
int front = 0;
int rear = 0;
for (i = 1; i <= G.n; ++i)
{
visited[i] = 0;
}

for (i = 1; i <= G.n; ++i)
{
if (!visited[i])
{
visited[i] = 1;
printf("%d ", G.adjlist[i].data);
rear = (rear + 1) % MaxSize;
que[rear] = G.adjlist[i].data;
while (front != rear)
{
front = (front + 1) % MaxSize;
j = que[front];
p = G.adjlist[j].firstarc;   //p指向出队顶点j的第一条边
while (p != NULL)  //将p的所有邻结点中未被访问的入队
{
if (!visited[p->adjvex])   //未被访问则进队
{
visited[p->adjvex] = 1;
printf("%d ", G.adjlist[p->adjvex].data);
rear = (rear + 1) % MaxSize;
que[rear] = p->adjvex;
}
p = p->nextarc;
}

}

}
}
printf("\n");
}

int main()
{
AGraph G;
CreateDG(G);
BFSTraverse(G);
return 0;
}


input

4 4
1 2
1 3
2 4
3 4


output

1 3 2 4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: