無向圖的深度廣度遍歷

在存儲有向圖的時候我已經詳細的解釋過了,爲了滿足一些讀者的需求,我把無向圖的鄰接表存儲方式的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;
}

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