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 <string.h>
#include <malloc.h>
#define maxnum 120
struct queue
{
int data[100];
int front;
int rear;
};
typedef struct queue Q;
typedef char VertexType;
typedef struct ArcNode
{
int adjvex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode
{
VertexType data;
ArcNode *firstarc;
}VNode, AdjList[maxnum];
typedef struct
{
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
int visited[maxnum] = {0};
void init(Q *myqueue)
{
myqueue->front = myqueue->rear = 0;
}
int isempty(Q *myqueue)
{
if (myqueue->front==myqueue->rear)
{
return 1;
}
else
{
return 0;
}
}
void enQueue(Q *myqueue, int num)
{
if (myqueue->rear == 100)
{
printf("失败");
return ;
}
else
{
myqueue->data[myqueue->rear] = num;
myqueue->rear += 1;
}
}
int DeQueue(Q *myqueue)
{
if (myqueue->front==myqueue->rear)
{
printf("失败");
return -1;
}
else
{
myqueue->front += 1;
return myqueue->data[myqueue->front-1];
}
}
int gethead(Q *myqueue)
{
if (myqueue->front == myqueue->rear)
{
printf("为空");
return -1;
}
else
{
return myqueue->data[myqueue->front];
}
}
void CreateALGraph(ALGraph &g, int arc, int vex)
{
int node[100];
for(int i=0;i<arc;i++)scanf("%d",&node[i]);
g.arcnum = arc;
g.vexnum = vex;
int v1, v2, i;
for(i = 0; i < vex; i++)
{
g.vertices[node[i]].firstarc = NULL;
}
for(i = 1; i <= arc; i++)
{
scanf("%d %d",&v1,&v2);
ArcNode *q = (ArcNode*)malloc(sizeof(ArcNode));
q->adjvex = v2;
q->nextarc = g.vertices[v1].firstarc;
g.vertices[v1].firstarc = q;
}
}
int BFS(ALGraph g, int i, int j)
{
Q q;
init(&q);
ArcNode *p;
int headvex;
if(!g.vexnum || !g.arcnum)return 0;
else
{
enQueue(&q,i);
while(!isempty(&q))
{
headvex=gethead(&q);
DeQueue(&q);
visited[headvex]=1;
p=g.vertices[headvex].firstarc;
while(p)
{
if(p->adjvex==j)return 1;
else if(visited[p->adjvex]==0)
{
visited[p->adjvex]=1;
enQueue(&q,p->adjvex);
}
p=p->nextarc;
}
}
}
return 0;
}
int main()
{
int m, n;
scanf("%d %d",&m,&n);
ALGraph g;
CreateALGraph(g, m, n);
int v1, v2;
scanf("%d %d",&v1,&v2);
int flag = BFS(g, v1, v2);
if(flag)
printf("yes\n");
else
printf("no\n");
return 0;
}