刚编写完,还很热乎呢,编译通过,呵呵,兴奋呢,就发上来了,大家一起学习哈。
这是一个深度优先遍历,和广度优先遍历的算法c实现。
#include "stdio.h"
#include "alloc.h"
typedef struct arc {
int addr;
struct arc *next;
}ARC;
typedef struct vertex{
int data;
ARC *firstarc;
}VERTEX;
#define maxnode 10
typedef VERTEX adj[maxnode];
int arcnum,nodenum;
int visited[maxnode];
void create(adj GL)
{
int i,j,k;
ARC * p;
for(i=0;i {
scanf("%d",&(GL.data));
GL.firstarc=NULL;
}
for(k=0;k {
scanf("%d,%d",&i,&j);/*every arc connects two nodes,here you input the addr of the node .*/
printf("\n");
p="malloc"(sizeof(ARC));
p->addr=j;p->next=GL.firstarc;GL.firstarc=p;
p="malloc"(sizeof(ARC));
p->addr=i;p->next=GL[j].firstarc;GL[j].firstarc=p;
}
}
adjdfs(adj GL,int v)
{
int i,j;
for(i=0;i {
visited=0;/*if visited ,1;else 0.*/
}
dfs(GL,v);
}
dfs(adj GL,int v)
{
ARC *p;
if(visited[v]!=1)
{
visited[v]=1;
/*visited*/
printf("%d\n",GL[v].data);
}
p=GL[v].firstarc;
while(p!=NULL){v=p->addr;
if(visited[v]!=1)
{dfs(GL,v);}
}
p=p->next;
}
adjbfs(adj GL,int v)
{
int i,j,k,q[maxnode];
int front="0",rear=0;
ARC *p;
p=GL[v].firstarc;
q[rear]=v;
printf("%d *\n",GL[v].data);
rear++;
while(front!=rear)
{
k=q[front];
while(p!=NULL) {
if(visited[k]!=1)
{visited[k]=1;
printf("%d *",GL[k].data);
q[rear]=p->addr;
rear++;
}
p="p-">next;
front++;
}
}
}
main()
{
adj GL;
int i,v;
printf("please input the number of arc and node in order to create a gragh \n");
scanf("%d,%d",&arcnum,&nodenum);
create(GL);
printf("dfs and input the node from which to start the dfs \n");
scanf("%d",&v);
adjdfs(GL,v);
for(i=0;i {visited=0;}
/*adjbfs(GL,v);*/
}
用户1451188 2007-12-30 18:29
这是数据结构的程序,抽象的图。呵呵
用户741296 2007-12-30 13:56