基于邻接表的广度优先搜索遍历
#include<stdio.h> #include<stdlib.h> #include<string.h> int k,h[110],mark; struct M { int data; struct M *next; }*head[110]; void init() { int i; for(i = 0; i < k; i++) { head[i] = (struct M *)malloc(sizeof(struct M)); head[i]->next = NULL; head[i]->data = -1; } } void link(int u,int v) { struct M *p1,*p2,*q; q = (struct M *)malloc(sizeof(struct M)); q->next = NULL; q->data = v; for(p1 = head[u],p2 = p1->next; p2 != NULL; p1 = p1->next,p2 = p2->next) { if(p1->data < v && p2->data > v) { q->next = p1->next; p1->next = q; return; } else if(p2->data == v) { free(q); return; } } p1->next = q; } void seek(int mb) { struct M *p; int q[105],s,e; s = e = 0; q[e++] = mb; while(s < e) { mb = q[s++]; if(mark) { mark = 0; printf("%d",mb); } else printf(" %d",mb); for(p = head[mb]->next; p != NULL; p = p->next) { if(!h[p->data]) { h[p->data] = 1; q[e++] = p->data; } } } } int main() { int js,m,t,i,u,v; struct M *p; scanf("%d",&js); while(js--) { scanf("%d %d %d",&k,&m,&t); init(); for(i = 0; i < m; i++) { scanf("%d %d",&u,&v); link(u,v); link(v,u); } memset(h,0,sizeof(h)); h[t] = 1; mark = 1; seek(t); printf("\n"); } return 0; }