圖的廣度優先遍曆 (10分)
成績: 10 / 折扣: 0.8
圖的廣度優先遍曆(10分)
本實驗實現鄰接表表示下無向圖的廣度優先遍曆。程式的輸入是圖的頂點序列和邊序列(頂點序列以*為結束標誌,邊序列以-1,-1為結束標誌)。程式的輸出為圖的鄰接表和廣度優先遍曆序列。例如:的圖:
程式輸入為:
a
b
c
d
e
f
*
0,1
0,4
1,4
1,5
2,3
2,5
3,5
-1,-1
程式的輸出為:
the ALGraph is
a 4 1
b 5 4 0
c 5 3
d 5 2
e 1 0
f 3 2 1
the Breadth-First-Seacrh list:aebfdc
#include <stdio.h>#include <stdlib.h>#include <string.h>struct arcnode{ int num; struct arcnode *next;};struct vnode{ int num; char c; int visited; struct arcnode *first;};CreateGraph(struct vnode *head[100],int k){ int a,b; char c; struct vnode *p,*q; struct arcnode *p1,*q1; k=0; while (1) { scanf("%c",&c); getchar(); if (c == '*') { break; } else { p = (struct vnode*)malloc(sizeof(struct vnode)); p->num = k; p->first = NULL; p->visited = 0; p->c = c; head[k++] = p; } } while (1) { scanf("%d,%d",&a,&b); if (a == -1 && b == -1) { break; } else { p1 = (struct arcnode*)malloc(sizeof(struct arcnode)); p1->num = b; if (head[a]->first != NULL) { p1->next = head[a]->first; } else { p1->next = NULL; } head[a]->first = p1; p1 = (struct arcnode*)malloc(sizeof(struct arcnode)); p1->num = a; if (head[b]->first != NULL) { p1->next = head[b]->first; } else { p1->next = NULL; } head[b]->first = p1; } } return k;}void PrintGraph(struct vnode *head[100],int k){ int i,j; struct arcnode *p; for (i = 0;i <= k;i++) { p = head[i]->first; for(j = 0;p != NULL;j++) { if (j == 0) { printf("%c ",head[i]->c); continue; } else { if (p->next != NULL) { printf("%d ",p->num); } else { printf("%d\n",p->num); } p = p->next; } } }}void BreadthSearch(struct vnode *head[100],struct vnode *cur,int k){ int i , flag = 0 , len=0 , list[100]; struct arcnode *p,*q; q = p = cur->first; while (p != NULL) { if (head[p->num]->visited != 1) { list[len++] = p->num; head[p->num]->visited = 1; printf("%c",head[p->num]->c); flag = 1; } p = p->next; } if (flag == 0) { return; } for (i = 0;i < len;i++) { BreadthSearch(head,head[list[i]],k); } for (i = 0;i <= k;i++) { if (head[i]->visited == 0) { printf("%c",head[i]->c); head[i]->visited = 1; BreadthSearch(head,head[i],k); } }}void main(){ int i,j,k=0; struct vnode *head[100]; k = CreateGraph(head,k); k--; printf("the ALGraph is\n"); PrintGraph(head,k); printf("the Breadth-First-Seacrh list:%c",head[0]->c); head[0]->visited = 1; BreadthSearch(head,head[0],k); printf("\n");}