數據結構20——基於圖的廣度優先搜索策略(耿7.11)

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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章