第12周-項目3 - 圖遍歷算法實現

問題及代碼:

實現圖遍歷算法,分別輸出如下圖結構的深度優先(DFS)遍歷序列和廣度優先遍歷(BFS)序列。 
這裏寫圖片描述 

測試時用的圖是這裏寫圖片描述,可以使用其他類型的圖代替。

1、深度優先遍歷——DFS

#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];
void DFS(ALGraph *G, int v)
{
    ArcNode *p;
    int w;
    visited[v]=1;
    printf("%d ", v);
    p=G->adjlist[v].firstarc;
    while (p!=NULL)
    {
        w=p->adjvex;
        if (visited[w]==0)
            DFS(G,w);
        p=p->nextarc;
    }
}

int main()
{
    int i;
    ALGraph *G;
    int A[5][5]=
    {
        {0,1,0,1,0},
        {1,0,1,0,0},
        {0,1,0,1,1},
        {1,0,1,0,1},
        {0,0,1,1,0}
    };
    ArrayToList(A[0], 5, G);

    for(i=0; i<MAXV; i++) visited[i]=0;
    printf(" 由2開始深度遍歷:");
    DFS(G, 2);
    printf("\n");

    for(i=0; i<MAXV; i++) visited[i]=0;
    printf(" 由0開始深度遍歷:");
    DFS(G, 0);
    printf("\n");
    return 0;
}

2、廣度優先遍歷——BFS


#include <stdio.h>
#include <malloc.h>
#include "graph.h"

void BFS(ALGraph *G, int v)
{
    ArcNode *p;
    int w,i;
    int queue[MAXV],front=0,rear=0; //定義循環隊列
    int visited[MAXV];     //定義存放節點的訪問標誌的數組
    for (i=0; i<G->n; i++) visited[i]=0; //訪問標誌數組初始化
    printf("%2d",v);            //輸出被訪問頂點的編號
    visited[v]=1;                       //置已訪問標記
    rear=(rear+1)%MAXV;
    queue[rear]=v;              //v進隊
    while (front!=rear)         //若隊列不空時循環
    {
        front=(front+1)%MAXV;
        w=queue[front];             //出隊並賦給w
        p=G->adjlist[w].firstarc;   //找w的第一個的鄰接點
        while (p!=NULL)
        {
            if (visited[p->adjvex]==0)
            {
                printf("%2d",p->adjvex); //訪問之
                visited[p->adjvex]=1;
                rear=(rear+1)%MAXV; //該頂點進隊
                queue[rear]=p->adjvex;
            }
            p=p->nextarc;       //找下一個鄰接頂點
        }
    }
    printf("\n");
}


int main()
{
    ALGraph *G;
    int A[5][5]=
    {
        {0,1,0,1,0},
        {1,0,1,0,0},
        {0,1,0,1,1},
        {1,0,1,0,1},
        {0,0,1,1,0}
    };
    ArrayToList(A[0], 5, G);

    printf(" 由2開始廣度遍歷:");
    BFS(G, 2);

    printf(" 由0開始廣度遍歷:");
    BFS(G, 0);
    return 0;
}




輸出結果:


分析:

深度與廣度,自己畫畫會理解更深刻

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