Description
试基于图的广度优先搜索策略编写程序,判别以邻接表方式存储的有向图中,是否存在由顶点vi到vj的路径(i不等于j),
注意:程序中涉及的图的基本操作必须在此存储结构上实现。
Input
第一行输入有向图的顶点数n和边数m,用空格隔开;第二行输入顶点信息;分m行输入有向图边的信息,例如顶点对1,2表示从顶点1到顶点2的一条弧,最后一行输入待判别的顶点对vi,vj.(0<m,n<100)
Output
若有向图中存在由顶点vi到顶点vj的路径(i不等于j),则输出yes;否则输出no。
Sample Input
4 4
1 2 3 4
1 2
1 3
1 4
2 3
2 3
Sample Output
yes
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAX_VERTEX_NUM 1000
#define MAXSIZE 50
typedef struct
{
int ele[MAXSIZE];
int front;
int rear;
}Queue;
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode{
int data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct{
AdjList vertices;
int vexnum,arcnum;
}ALGraph;
void InitQueue(Queue*Q)
{
Q->front=Q->rear=0;
}
int EnQueue(Queue*Q,int x)
{
if((Q->rear+1)%MAXSIZE==Q->front)
return 0;
Q->ele[Q->rear]=x;
Q->rear=(Q->rear+1)%MAXSIZE;
return 1;
}
int DeQueue(Queue *Q,int *x)
{
if(Q->front==Q->rear)
return 0;
*x=Q->ele[Q->front];
Q->front=(Q->front+1)%MAXSIZE;
return 1;
}
int QueueEmpty(Queue Q)
{
if(Q.front==Q.rear)
return 1;
else return 0;
}
void CreatGraph(ALGraph *G)
{
int i,j,k;
ArcNode *p;
scanf("%d%d",&G->vexnum,&G->arcnum);
for(i=1;i<=G->vexnum;i++)
{scanf("%d",&G->vertices[i].data);
G->vertices[i].firstarc=NULL;
}
for(k=1;k<=G->arcnum;k++)
{
p=(ArcNode*)malloc(sizeof(ArcNode));
scanf("%d%d", &i, &j);
p->adjvex = j;
p->nextarc=G->vertices[i].firstarc;
G->vertices[i].firstarc=p;
}
}
int BFS(ALGraph G, int i, int j)
{
ArcNode *p;
Queue Q;
int e,k;
InitQueue(&Q);
EnQueue(&Q,i);
int visited[MAX_VERTEX_NUM];
while(!QueueEmpty(Q))//队列不为空时
{
DeQueue(&Q,&e);//队头元素出队并置为e
visited[e] = 1;//标记被访问过的顶点
p = G.vertices[e].firstarc;
for(; p != NULL; p = p -> nextarc)
{
k = p -> adjvex;//当前弧所指向顶点的位置
if(k == j)
return 1;
else if(!visited[k])//当前顶点未被访问过
EnQueue(&Q,k);
}
}
return 0;
}
int main()
{
ALGraph G;
int i,j;
CreatGraph(&G);
scanf("%d%d",&i,&j);
if(BFS(G,i,j))
{
printf("yes");
}
else printf("no");
return 0;
}