无向图的深度广度遍历

在存储有向图的时候我已经详细的解释过了,为了满足一些读者的需求,我把无向图的邻接表存储方式的c语言代码发出供大家参考
这个图的结构如下,只是把单向箭头改成双向箭头
在这里插入图片描述

#include<stdlib.h>
#include <stdio.h>
#define max 20
typedef struct  arcNode{
    int adjvex;
    struct arcNode *next;
}arcNode;
typedef struct vNode{
    char data;
    arcNode *firstArc;
}vNode;
typedef struct graph{
    vNode adjlist[max];
    int n,e;
}graph;
graph *G;
typedef struct arc{
    int head;
    int tail;
}arc;
arc arclist[max];
int count=0;
int flag=0;//record   isConnected
int visit[max]={0};
void createArc(int k,int head,int tail){
    arclist[k].head = head;
    arclist[k].tail = tail;
}
void createGraph(graph *G,int head,int tail){//创建树

    arcNode *e;
    e = (arcNode*)malloc(sizeof(arcNode));
    e->adjvex = head;
    e->next = G->adjlist[tail].firstArc;
    G->adjlist[tail].firstArc = e;//finish the arc from head to tail
    
    e = (arcNode*)malloc(sizeof(arcNode));
    e->adjvex = tail;
    e->next = G->adjlist[head].firstArc;
    G->adjlist[head].firstArc = e;
    
    
 }
void Visit(int v){
    printf("%c\t",G->adjlist[v].data);
}
void DFS(graph *G,int v){
    arcNode *p;
    visit[v] = 1;
    Visit(v);
    p = G->adjlist[v].firstArc;
    while(p!=NULL){
        if(visit[p->adjvex]==0){
            DFS(G, p->adjvex);
        }
        p = p->next;
    }
}
void BFS(graph *G,int v){
    arcNode *p;
    int queue[max];
    int front,rear;
    int j;
    front = rear = 0;
    Visit(v);
    visit[v] = 1;
    rear = (rear+1)%max;
    queue[rear] = v;
    while(front!=rear){
        front = (front+1)%max;
        j = queue[front];
        p = G->adjlist[j].firstArc;//这个地方下表是j一定不要填错了
        while (p!=NULL) {
             if(visit[p->adjvex]==0){
                Visit(p->adjvex);
                visit[p->adjvex] = 1;
                rear = (rear+1)%max;
                queue[rear] = p->adjvex;
            }
            p = p->next;
        }
    }
}
    return j;
}

int main(int argc, const char * argv[]) {
    int i[max]={0,0,0,0,1,1,2};
    int j[max]={1,2,3,4,2,4,3};
    G = (graph*)malloc(sizeof(graph));
    G->e = 7;
    G->n = 5;
    for(int k=0;k<G->n;k++){//inital the head of link
        G->adjlist[k].firstArc = NULL;
        G->adjlist[k].data = '0'+k;
    }
    for(int k=0;k<G->e;k++){//automatic the vertex inputing
           createArc(k,i[k],j[k]);
       }
    for(int k=0;k<G->e;k++){//insert  node into graph
         createGraph(G,arclist[k].head,arclist[k].tail);
    }
   
    DFS(G,0);//深度优先遍历,从顶点0开始
    BFS(G,0);//广度优先遍历 ,从顶点0开始
    return 0;
}

在这里插入代码片
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章