您的位置:首页 > 编程语言 > C语言/C++

图--广度优先遍历/深度优先遍历(c语言实现)

2015-05-08 14:37 459 查看
  //不能通过编译,没有引入队列头文件
1 #include<stdlib.h>
#define MAX_VERTEX_NUM;
typedef int infoType;
typedef int vertexType;

typedef struct ArcNode{
int adjvex;
struct ArcNode *next;
infoType *weight;
}Arcnode;

typedef struct VNode{
vertexType data;
Arcnode *firstarc;
}VNode;

//VNode G[MAX_VERTEX_NUM];
void getdata(VNode v);

//图的创建
void createGraph(int n,VNode G[]){
int i,e;
Arcnode *p,*q;
printf("input the information of the vertex\n");
for(i=0;i<n;i++){
getdata(G[i]);
G[i].firstarc=NULL;
}
for(i=0;i<n;i++){
printf("create the edges for the %dth vertex\n",i);
scanf("%d",&e);
while(e!=-1){
p=(Arcnode *)malloc(sizeof(Arcnode));
p->next=NULL;
p->adjvex=e;
if(G[i].firstarc==NULL){
G[i].firstarc=p;
}else{
q->next=p;
}
q=p;
scanf("%d",&e);
}
}
}

//图的遍历(1)--深度优先搜索
void DFS(VNode g[],int v,int visited[]){
int w;
visit(v);
visited[v]=1;
w=FirstAdj(g,v);
while(w!=-1){
if(visited[w]==0)
DFS(g,w,visited);
w=nextAdj(g,v);
}

}

void DFSGraph(VNode g[],int visited[],int n){
int i;
for(i=0;i<n;i++){
visited[i]=0;
}
for(i=0;i<n;i++){
if(visited[i]==0)
DFS(g,i,visited);
}
}

//图的遍历(2)--广度优先搜索

void BFS(VNode G[],int v,int visited[]){
int w;
visit(v);
visited[v]=1;
EnQueue(q,v);
while(!emptyA(q)){
Dequeue(&q,&v);
w=FirstAdj(g,v);
while(w!=-1){
if(visited[w]==0){
visit(w);
EnQueue(q,w);
visited[w]=1;
}
w=NextAdj(g,v);
}
}
}

void Travel_BFS(VNode g[],int visited[],int n){
int i;
for(i=0;i<n;i++){
visited[i]=0;
}
for(i=0;i<n;i++){
if(visited[i]==0)
BFS(g,i,visited);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: