# 逻辑算法大赛辅导--图的遍历

zengyiCSTC 2004-02-16 11:35:13

#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include"dos.h"
#define M 60
/*定义链表中的结点类型*/
typedef struct node
{
int vex; /* 顶点域 */
}JD;
/*定义表头结点*/
typedef struct tnode
{
int data; /*数据域*/
//char data;
}TD;
/*建立无向图的邻接表*/
{
JD *p;
int i,j,k;
for(k=1;k<=n;k++)

printf("please input the node that are conected with the known node\n");
printf("(Input 0,0 to finish the enter work)");
scanf("%d,%d",&i,&j); /*输入一条边相关联的两个表结点*/
while((i>0)&&(j>0)) /*结束时以（0，0）表示*/
{
p=(JD *)malloc(sizeof(JD)); /*开辟新单元生成新结点*/
p->vex=j;
p=(JD *)malloc(sizeof(JD));
p->vex=i;
printf("please input the node that are conected with the node\n");
scanf("%d,%d",&i,&j); /*继续输入两个邻接顶点*/
}

}
/*广度优先遍历函数生成*/
void bfs(TD g[], int v, int c[])
{
int q[M],r=0,f=0; /*f指向队首r指向队尾*/
JD *p;
c[v]=1;
printf("the visited node is %d\n",v);
q[0]=v;
while(f<=r) /*队列不空*/
{
v=q[f++]; /*访问过的顶点出队*/
while(p!=NULL)
{
v=p->vex;
if(c[v]==0)
{
c[v]=1;
printf("%d\n",v);
q[++r]=v; /*访问该顶点并近队*/
}
}
}
}
/*深度优先递归函数*/
void dfs(TD g[], int v, int c[])
{
JD *p;
int i;
c[v]=1;
printf(" the dfs node is %d\n",v); /* 访问顶点v*/
{
i=p->vex; /*得出p指针所指邻接点的序号*/
if(c[i]==0)
dfs(g,i,c); /*递归调用*/
}
}
/*遍历图*/
void blt(TD g[], int n)
{
int v;
int c[M];
for(v=1;v<=n;v++)
c[v]=0;/*访问标识数组初始化*/
for(v=1;v<=n;v++)
if(c[v]==0)
dfs(g,v,c); /*调用dfs函数*/
}
/*主函数*/
void main(void)
{
clrscr();
int n,x,v,y;
int c[10];
TD a[10];
scanf("%d",&n);
creatljb(a,n);
first:
scanf("%d",&v);
if(v>10)
{
printf("ERROR!! WRONG INPUT NUMBER\n");
goto first;
}
else
{
/* printf("please input y : ");
scanf("%d",&y); */
printf("please input what you want to do (x=1,2,3) :\n ");
printf("(1:bfs; 2:dfs; 3:break;)"); /*选择遍历类型*/
scanf("%d",&x);
switch(x){
case 1 : bfs(a,v,c);
case 2 : dfs(a,v,c);
blt(a,n);
case 3 : printf("ESC");
}
}
printf(" Go through the Graph: finished!");
getch(); /*得一字符结束*/
}
...全文
39 点赞 收藏 3

3 条回复

csdnshao 2004-03-30
mark

wht5555 2004-03-19

duduliao 2004-03-16

222

2004-02-16 11:35