SDUTACM 图的深度遍历

来源:互联网 发布:淘宝耳环好卖吗 编辑:程序博客网 时间:2024/06/06 03:52

题目描述

请定一个无向图,顶点编号从0到n-1,用深度优先搜索(DFS),遍历并输出。遍历时,先遍历节点编号小的。

输入

输入第一行为整数n(0 < n < 100),表示数据的组数。 对于每组数据,第一行是两个整数k,m(0 < k < 100,0 < m < k*k),表示有m条边,k个顶点。 下面的m行,每行是空格隔开的两个整数u,v,表示一条连接u,v顶点的无向边。

输出

输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示DFS的遍历结果。

示例输入

14 40 10 20 32 3

示例输出

0 1 2 3

提示

 
#include<stdio.h>#include<stdlib.h>#include<string.h>//flag标记输出是否是第一个,以便符合输出格式//vis数组标记顶点是否已访问int vis[1000],flag;struct hh{    int data;    struct hh *next;};struct h{    int n;    int e;    struct hh Point[110];};struct h *creat(struct h *g){    struct hh *p,*q1,*q2;    int i,v,u;   //初始化链表顶点    for(i=0;i<g->n;i++)    {        g->Point[i].data=i;        g->Point[i].next=NULL;    }    //将有连接的两个顶点连接在一起    for(i=0;i<g->e;i++)    {        scanf("%d%d",&u,&v);        //将u连接到v上p=(struct hh *)malloc(sizeof(struct hh));p->data=u;q1=&g->Point[v];while(q1->next!=NULL)q1=q1->next;p->next=q1->next;q1->next=p;q1=p;        //将v连接到u上        p=(struct hh *)malloc(sizeof(struct hh));p->data=v;        q2=&g->Point[u];while(q2->next!=NULL)q2=q2->next;p->next=q2->next;q2->next=p;q2=p;    }return g;};void sort(struct hh *head){struct hh *p,*q;    int k=0;while(k=!k){p=head;q=p->next;while(q){            if(p->data>q->data){int t;t=p->data;p->data=q->data;q->data=t;k=0;}else{p=p->next;q=q->next;}}}}void DFS(struct h *g,int v){struct hh *p;//标记已访问vis[v]=1;//控制输出if(flag==1){printf("%d",v);flag=0;}elseprintf(" %d",v);//找到和当前v有连接的下一个顶点p=g->Point[v].next;//将和v有联系的几个顶点从小到大排序sort(p);while(p!=NULL){if(vis[p->data]==0)DFS(g,p->data);p=p->next;}}int main(){    int m,i;    struct h *g;    g=(struct h *)malloc(sizeof(struct h));    scanf("%d",&m);    for(i=0;i<m;i++)    {//初始化flag        flag=1;//输入边数和顶点数        scanf("%d%d",&g->n,&g->e);//初始化vis数组        memset(vis,0,sizeof(vis));//调用creat函数创建图        g=creat(g);//调用深度优先搜索DFS(g,0);printf("\n");    }return 0;}

0 0
原创粉丝点击