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> #define Max 200 typedef struct data{ int num; struct data *next; }data; typedef struct queue{ struct data *head; struct data *rear; }queue; typedef struct ArcNode{ int adjvex; struct ArcNode *nextarc; }ArcNode; typedef struct VNode{ int code; struct ArcNode *firstarc; }VNode,AdjList[Max]; typedef struct ALGraph{ AdjList vertices; int vexnum; int arcnum; }ALGraph; int visited[Max] = {0}, flag = 1; void initqueue(queue *Q, int x){ data *p = (data*)malloc(sizeof(data)); p->num = 0; p->next = NULL; Q->head = p; Q->rear = p; } void push(queue *Q, int n){ data *p, *q; p = (data*)malloc(sizeof(data)); p->num = n; q = Q->head->next; if(q == NULL){ p->next = NULL; Q->head->next = p; Q->rear = p; } else{ Q->head->next = p; p->next = q; } } int pop(queue *Q){ data *p, *q; int codenum; p = Q->head; q = Q->rear; codenum = q->num; while(p->next != q){ p = p->next; } Q->rear = p; Q->rear->next = NULL; free(q); return codenum; } int emptyqueue(queue *Q){ if(Q->rear == Q->head) return 1; else return 0; } void CreateGraph(ALGraph *List){ int i, x, y; scanf("%d%d",&x,&y); List->vexnum = x; List->arcnum = y; for(i = 1; i <= List->vexnum; i++){ scanf("%d",&List->vertices[i].code); List->vertices[i].firstarc = NULL; } for(i = 1; i <= List->arcnum; i++){ ArcNode *p = (ArcNode*)malloc(sizeof(ArcNode)); scanf("%d%d",&x, &y); p->adjvex = y; p->nextarc = List->vertices[x].firstarc; List->vertices[x].firstarc = p; } } int BFS(queue *Q, ALGraph *List, int x, int y){ int i, tmp, tmp1; ArcNode *p; while(!emptyqueue(Q) || flag == 1){ flag = 0; tmp = pop(Q); visited[tmp] = 1; p = List->vertices[tmp].firstarc; for(; p != NULL; p = p->nextarc){ tmp1 = p->adjvex; if(tmp1 == y) return 1; else if(!visited[tmp1]) push(Q, tmp1); } } return 0; } int main(){ ALGraph List; queue *Q = (queue*)malloc(sizeof(queue)); int x, y; CreateGraph(&List); scanf("%d%d",&x,&y); initqueue(Q, x); push(Q,x); if(BFS(Q, &List, x, y)){ printf("yes\n"); } else{ printf("no\n"); } return 0; }