#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
const int Len=105;
const int maxn = 1e5 + 10;
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode {
int adjv;
int pow;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[Len];
typedef struct Node{
int nv;//点
int ne;//边
int visited[Len];
AdjList G[Len];//邻接表
}*graph;//图
typedef struct
{
int data[maxn];
int rear;
int front;
}Queue;//队列
graph CreateGraph(int n)//建图
{
int i;
graph g = (graph)malloc(sizeof(struct Node));
g->nv=n;
g->ne=0;
for (i=0;i<g->nv;++i){
g->G[i]->FirstEdge=NULL;
}
for (i=0;i<g->nv;++i){
g->visited[i]=0;
}
return g;
}
void InsertEdge(graph g,int s,int e,int pow)//插入边
{
PtrToAdjVNode newb;
newb=(PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
newb->adjv=e;
newb->pow=pow;
newb->Next=g->G[s]->FirstEdge;
g->G[s]->FirstEdge=newb;
}
Queue* MakeQueue()//建队列
{
Queue* Q=(Queue*)malloc(sizeof(Queue));
Q->front=0;
Q->rear=0;
return Q;
}
void AddQ(Queue *PtrlQ,int item)//入队列
{
if(PtrlQ->rear+1==maxn){
printf("The Queue is full");
return ;
}
PtrlQ->rear=PtrlQ->rear+1;
PtrlQ->data[PtrlQ->rear]=item;
}
int DeleteQ ( Queue *PtrQ )//出队列
{
if ( PtrQ->front == PtrQ->rear ) {
printf("The Queue is empty");
return NULL;
}
else {
PtrQ->front = PtrQ->front+1;
return PtrQ->data[PtrQ->front];
}
}
int isEmpty( Queue *PtrlQ )//队列是否为空
{
if(PtrlQ->front == PtrlQ->rear) return 0;
else return 1;
}
int isFull( Queue *PtrlQ )//队列是否为满
{
if(PtrlQ->rear+1==maxn) return 0;
else return 1;
}
void BFS(graph g,int n,Queue *q)
{
g->visited[n]=1;
AddQ(q,n);
while(isEmpty(q)==1){
int m=DeleteQ(q);
printf("V%d ",m);
while(g->G[m]->FirstEdge!=NULL){
if(g->visited[g->G[m]->FirstEdge->adjv]==0){
AddQ(q,g->G[m]->FirstEdge->adjv);
g->visited[g->G[m]->FirstEdge->adjv]=1;
}
g->G[m]->FirstEdge=g->G[m]->FirstEdge->Next;
}
}
}
int main(){
int n,i,q,b,c,d,m,s,sum=1;
// freopen("E:/c++/input.txt", "r", stdin);
// freopen("E:/c++/output.txt", "w", stdout);
scanf("%d %d",&s,&q);
graph g=CreateGraph(s);
graph gcopy=CreateGraph(s);
Queue *queue=MakeQueue();
for(i=0;i<q;++i){
scanf("%d %d %d",&b,&c,&d);
InsertEdge(g,b,c,d);
InsertEdge(gcopy,b,c,d);
}
while(~scanf("%d",&n),n!=-1){
for (i=0;i<g->nv;++i){
g->visited[i]=0;
}
printf("BFS From V%d:",n);
BFS(g,n,queue);
printf("\n");
for (i=0;i<g->nv;++i){
g->G[i]->FirstEdge=gcopy->G[i]->FirstEdge;
}
}
// fclose(stdin);//关闭重定向输入
// fclose(stdout);//关闭重定向输出
system("pause");
return 0;
}
BFS(邻接表)
最新推荐文章于 2024-06-01 20:06:44 发布