第十二週上機實踐—項目4—利用遍歷思想求解圖問題

</pre><pre class="cpp" name="code">/*
 *Copyright(c) 2015,煙臺大學計算機學院
 *All rights reserved.
 *文件名稱:test.cpp
 *作者:林莉
 *完成日期:2015年11月20日
 *版本:v1.0
 *
 *問題描述:假設圖G採用鄰接表存儲,實現所要求的算法。
 *輸入描述:無
 *程序輸出:所得結果。
 */

1.頭文件:graph.h,包含定義圖數據結構的代碼、宏定義、要實現算法的函數的聲明;

#ifndef GRAPH_H_INCLUDED
#define GRAPH_H_INCLUDED

#define MAXV 100                //最大頂點個數
#define INF 32767       //INF表示∞
typedef int InfoType;

//以下定義鄰接矩陣類型
typedef struct
{
    int no;                     //頂點編號
    InfoType info;              //頂點其他信息,在此存放帶權圖權值
} VertexType;                   //頂點類型

typedef struct                  //圖的定義
{
    int edges[MAXV][MAXV];      //鄰接矩陣
    int n,e;                    //頂點數,弧數
    VertexType vexs[MAXV];      //存放頂點信息
} MGraph;                       //圖的鄰接矩陣類型

//以下定義鄰接表類型
typedef struct ANode            //弧的結點結構類型
{
    int adjvex;                 //該弧的終點位置
    struct ANode *nextarc;      //指向下一條弧的指針
    InfoType info;              //該弧的相關信息,這裏用於存放權值
} ArcNode;

typedef int Vertex;

typedef struct Vnode            //鄰接表頭結點的類型
{
    Vertex data;                //頂點信息
    int count;                  //存放頂點入度,只在拓撲排序中用
    ArcNode *firstarc;          //指向第一條弧
} VNode;

typedef VNode AdjList[MAXV];    //AdjList是鄰接表類型

typedef struct
{
    AdjList adjlist;            //鄰接表
    int n,e;                    //圖中頂點數n和邊數e
} ALGraph;                      //圖的鄰接表類型

//功能:由一個反映圖中頂點鄰接關係的二維數組,構造出用鄰接矩陣存儲的圖
//參數:Arr - 數組名,由於形式參數爲二維數組時必須給出每行的元素個數,在此將參數Arr聲明爲一維數組名(指向int的指針)
//      n - 矩陣的階數
//      g - 要構造出來的鄰接矩陣數據結構
void ArrayToMat(int *Arr, int n, MGraph &g); //用普通數組構造圖的鄰接矩陣
void ArrayToList(int *Arr, int n, ALGraph *&); //用普通數組構造圖的鄰接表
void MatToList(MGraph g,ALGraph *&G);//將鄰接矩陣g轉換成鄰接表G
void ListToMat(ALGraph *G,MGraph &g);//將鄰接表G轉換成鄰接矩陣g
void DispMat(MGraph g);//輸出鄰接矩陣g
void DispAdj(ALGraph *G);//輸出鄰接表G

#endif // GRAPH_H_INCLUDED


 

2.源文件:graph.cpp,包含實現各種算法的函數的定義

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

//功能:由一個反映圖中頂點鄰接關係的二維數組,構造出用鄰接矩陣存儲的圖
//參數:Arr - 數組名,由於形式參數爲二維數組時必須給出每行的元素個數,在此將參數Arr聲明爲一維數組名(指向int的指針)
//      n - 矩陣的階數
//      g - 要構造出來的鄰接矩陣數據結構
void ArrayToMat(int *Arr, int n, MGraph &g)
{
    int i,j,count=0;  //count用於統計邊數,即矩陣中非0元素個數
    g.n=n;
    for (i=0; i<g.n; i++)
        for (j=0; j<g.n; j++)
        {
            g.edges[i][j]=Arr[i*n+j]; //將Arr看作n×n的二維數組,Arr[i*n+j]即是Arr[i][j],計算存儲位置的功夫在此應用
            if(g.edges[i][j]!=0)
                count++;
        }
    g.e=count;
}

void ArrayToList(int *Arr, int n, ALGraph *&G)
{
    int i,j,count=0;  //count用於統計邊數,即矩陣中非0元素個數
    ArcNode *p;
    G=(ALGraph *)malloc(sizeof(ALGraph));
    G->n=n;
    for (i=0; i<n; i++)                 //給鄰接表中所有頭節點的指針域置初值
        G->adjlist[i].firstarc=NULL;
    for (i=0; i<n; i++)                 //檢查鄰接矩陣中每個元素
        for (j=n-1; j>=0; j--)
            if (Arr[i*n+j]!=0)      //存在一條邊,將Arr看作n×n的二維數組,Arr[i*n+j]即是Arr[i][j]
            {
                p=(ArcNode *)malloc(sizeof(ArcNode));   //創建一個節點*p
                p->adjvex=j;
                p->info=Arr[i*n+j];
                p->nextarc=G->adjlist[i].firstarc;      //採用頭插法插入*p
                G->adjlist[i].firstarc=p;
            }

    G->e=count;
}

void MatToList(MGraph g, ALGraph *&G)
//將鄰接矩陣g轉換成鄰接表G
{
    int i,j;
    ArcNode *p;
    G=(ALGraph *)malloc(sizeof(ALGraph));
    for (i=0; i<g.n; i++)                   //給鄰接表中所有頭節點的指針域置初值
        G->adjlist[i].firstarc=NULL;
    for (i=0; i<g.n; i++)                   //檢查鄰接矩陣中每個元素
        for (j=g.n-1; j>=0; j--)
            if (g.edges[i][j]!=0)       //存在一條邊
            {
                p=(ArcNode *)malloc(sizeof(ArcNode));   //創建一個節點*p
                p->adjvex=j;
                p->info=g.edges[i][j];
                p->nextarc=G->adjlist[i].firstarc;      //採用頭插法插入*p
                G->adjlist[i].firstarc=p;
            }
    G->n=g.n;
    G->e=g.e;
}

void ListToMat(ALGraph *G,MGraph &g)
//將鄰接表G轉換成鄰接矩陣g
{
    int i,j;
    ArcNode *p;
    g.n=G->n;   //根據一樓同學“舉報”改的。g.n未賦值,下面的初始化不起作用
    g.e=G->e;
    for (i=0; i<g.n; i++)   //先初始化鄰接矩陣
        for (j=0; j<g.n; j++)
            g.edges[i][j]=0;
    for (i=0; i<G->n; i++)  //根據鄰接表,爲鄰接矩陣賦值
    {
        p=G->adjlist[i].firstarc;
        while (p!=NULL)
        {
            g.edges[i][p->adjvex]=p->info;
            p=p->nextarc;
        }
    }
}

void DispMat(MGraph g)
//輸出鄰接矩陣g
{
    int i,j;
    for (i=0; i<g.n; i++)
    {
        for (j=0; j<g.n; j++)
            if (g.edges[i][j]==INF)
                printf("%3s","∞");
            else
                printf("%3d",g.edges[i][j]);
        printf("\n");
    }
}

void DispAdj(ALGraph *G)
//輸出鄰接表G
{
    int i;
    ArcNode *p;
    for (i=0; i<G->n; i++)
    {
        p=G->adjlist[i].firstarc;
        printf("%3d: ",i);
        while (p!=NULL)
        {
            printf("-->%d/%d ",p->adjvex,p->info);
            p=p->nextarc;
        }
        printf("\n");
    }
}

3.在同一項目(project)中建立一個源文件(如main.cpp),編制main函數,完成相關的測試工作

[1*]應用圖的深度優先遍歷思路求解問題。

(1)是否有簡單路徑?
問題:假設圖G採用鄰接表存儲,設計一個算法,判斷頂點u到v是否有簡單路徑。

#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];     //定義存放節點的訪問標誌的全局數組
void ExistPath(ALGraph *G,int u,int v, bool &has)
{
    int w;
    ArcNode *p;
    visited[u]=1;
    if(u==v)
    {
        has=true;
        return;
    }
    p=G->adjlist[u].firstarc;
    while (p!=NULL)
    {
        w=p->adjvex;
        if (visited[w]==0)
            ExistPath(G,w,v,has);
        p=p->nextarc;
    }
}

void HasPath(ALGraph *G,int u,int v)
{
    int i;
    bool flag = false;
    for (i=0; i<G->n; i++)
        visited[i]=0; //訪問標誌數組初始化
    ExistPath(G,u,v,flag);
    printf(" 從 %d 到 %d ", u, v);
    if(flag)
        printf("有簡單路徑\n");
    else
        printf("無簡單路徑\n");
}

int main()
{
    ALGraph *G;
    int A[5][5]=
    {
        {0,0,0,0,0},
        {0,0,1,0,0},
        {0,0,0,1,1},
        {0,0,0,0,0},
        {1,0,0,1,0},
    };  //請畫出對應的有向圖
    ArrayToList(A[0], 5, G);
    HasPath(G, 1, 0);
    HasPath(G, 4, 1);
    return 0;
}1


運行結果:

(2)輸出簡單路徑
問題:假設圖G採用鄰接表存儲,設計一個算法輸出圖G中從頂點u到v的一條簡單路徑(假設圖G中從頂點u到v至少有一條簡單路徑)。

#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];     //定義存放節點的訪問標誌的全局數組
void FindAPath(ALGraph *G,int u,int v,int path[],int d)
{
    //d表示path中的路徑長度,初始爲-1
    int w,i;
    ArcNode *p;
    visited[u]=1;
    d++;
    path[d]=u;  //路徑長度d增1,頂點u加入到路徑中
    if (u==v)   //找到一條路徑後輸出並返回
    {
        printf("一條簡單路徑爲:");
        for (i=0; i<=d; i++)
            printf("%d ",path[i]);
        printf("\n");
        return;         //找到一條路徑後返回
    }
    p=G->adjlist[u].firstarc;  //p指向頂點u的第一個相鄰點
    while (p!=NULL)
    {
        w=p->adjvex;    //相鄰點的編號爲w
        if (visited[w]==0)
            FindAPath(G,w,v,path,d);
        p=p->nextarc;   //p指向頂點u的下一個相鄰點
    }
}

void APath(ALGraph *G,int u,int v)
{
    int i;
    int path[MAXV];
    for (i=0; i<G->n; i++)
        visited[i]=0; //訪問標誌數組初始化
    FindAPath(G,u,v,path,-1);  //d初值爲-1,調用時d++,即變成了0
}

int main()
{

    ALGraph *G;
    int A[5][5]=
    {
        {0,0,0,0,0},
        {0,0,1,0,0},
        {0,0,0,1,1},
        {0,0,0,0,0},
        {1,0,0,1,0},
    };  //請畫出對應的有向圖
    ArrayToList(A[0], 5, G);
    APath(G, 1, 0);
    APath(G, 4, 1);
    return 0;
}


運行結果:

(3)輸出所有路徑
問題:輸出從頂點u到v的所有簡單路徑。

#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];     //定義存放節點的訪問標誌的全局數組
void FindPaths(ALGraph *G,int u,int v,int path[],int d)
//d是到當前爲止已走過的路徑長度,調用時初值爲-1
{
    int w,i;
    ArcNode *p;
    visited[u]=1;
    d++;            //路徑長度增1
    path[d]=u;              //將當前頂點添加到路徑中
    if (u==v && d>1)            //輸出一條路徑
    {
        printf("  ");
        for (i=0; i<=d; i++)
            printf("%d ",path[i]);
        printf("\n");
    }
    p=G->adjlist[u].firstarc; //p指向u的第一條邊
    while(p!=NULL)
    {
        w=p->adjvex;     //w爲u的鄰接頂點
        if (visited[w]==0)      //若頂點未標記訪問,則遞歸訪問之
            FindPaths(G,w,v,path,d);
        p=p->nextarc; //找u的下一個鄰接頂點
    }
    visited[u]=0;   //恢復環境
}


void DispPaths(ALGraph *G,int u,int v)
{
    int i;
    int path[MAXV];
    for (i=0; i<G->n; i++)
        visited[i]=0; //訪問標誌數組初始化
    printf("從%d到%d的所有路徑:\n",u,v);
    FindPaths(G,u,v,path,-1);
    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);
    DispPaths(G, 1, 4);
    return 0;
}


運行結果:

(4)輸出一些簡單迴路
問題:輸出圖G中從頂點u到v的長度爲s的所有簡單路徑。

#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];     //定義存放節點的訪問標誌的全局數組
void SomePaths(ALGraph *G,int u,int v,int s, int path[],int d)
//d是到當前爲止已走過的路徑長度,調用時初值爲-1
{
    int w,i;
    ArcNode *p;
    visited[u]=1;
    d++;            //路徑長度增1
    path[d]=u;              //將當前頂點添加到路徑中
    if (u==v && d==s)           //輸出一條路徑
    {
        printf("  ");
        for (i=0; i<=d; i++)
            printf("%d ",path[i]);
        printf("\n");
    }
    p=G->adjlist[u].firstarc; //p指向u的第一條邊
    while(p!=NULL)
    {
        w=p->adjvex;     //w爲u的鄰接頂點
        if (visited[w]==0)      //若頂點未標記訪問,則遞歸訪問之
            SomePaths(G,w,v,s,path,d);
        p=p->nextarc; //找u的下一個鄰接頂點
    }
    visited[u]=0;   //恢復環境
}

void DispSomePaths(ALGraph *G,int u,int v, int s)
{
    int i;
    int path[MAXV];
    for (i=0; i<G->n; i++)
        visited[i]=0; //訪問標誌數組初始化
    printf("從%d到%d長爲%d的路徑:\n",u,v,s);
    SomePaths(G,u,v,s,path,-1);
    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);
    DispSomePaths(G, 1, 4, 3);
    return 0;
}


運行結果:

(5)輸出通過一個節點的所有簡單迴路
問題:求圖中通過某頂點k的所有簡單迴路(若存在)

#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];       //全局變量
void DFSPath(ALGraph *G,int u,int v,int path[],int d)
//d是到當前爲止已走過的路徑長度,調用時初值爲-1
{
    int w,i;
    ArcNode *p;
    visited[u]=1;
    d++;
    path[d]=u;
    p=G->adjlist[u].firstarc;   //p指向頂點u的第一條邊
    while (p!=NULL)
    {
        w=p->adjvex;            //w爲頂點u的相鄰點
        if (w==v && d>0)        //找到一個迴路,輸出之
        {
            printf("  ");
            for (i=0; i<=d; i++)
                printf("%d ",path[i]);
            printf("%d \n",v);
        }
        if (visited[w]==0)          //w未訪問,則遞歸訪問之
            DFSPath(G,w,v,path,d);
        p=p->nextarc;       //找u的下一個鄰接頂點
    }
    visited[u]=0;           //恢復環境:使該頂點可重新使用
}

void FindCyclePath(ALGraph *G,int k)
//輸出經過頂點k的所有迴路
{
    int path[MAXV],i;
    for (i=0; i<G->n; i++)
        visited[i]=0; //訪問標誌數組初始化
    printf("經過頂點%d的所有迴路\n",k);
    DFSPath(G,k,k,path,-1);
    printf("\n");
}

int main()
{
    ALGraph *G;
    int A[5][5]=
    {
        {0,1,1,0,0},
        {0,0,1,0,0},
        {0,0,0,1,1},
        {0,0,0,0,1},
        {1,0,0,0,0}
    };  //請畫出對應的有向圖
    ArrayToList(A[0], 5, G);
    FindCyclePath(G, 0);
    return 0;
}


運行結果:

[2*]應用圖的廣度優先遍歷思路求解問題。

(6)最短路徑
問題:求不帶權連通圖G中從頂點u到頂點v的一條最短路徑。

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

typedef struct
{
    int data;                   //頂點編號
    int parent;                 //前一個頂點的位置
} QUERE;                        //非環形隊列類型

void ShortPath(ALGraph *G,int u,int v)
{
    //輸出從頂點u到頂點v的最短逆路徑
    ArcNode *p;
    int w,i;
    QUERE qu[MAXV];             //非環形隊列
    int front=-1,rear=-1;       //隊列的頭、尾指針
    int visited[MAXV];
    for (i=0; i<G->n; i++)      //訪問標記置初值0
        visited[i]=0;
    rear++;                     //頂點u進隊
    qu[rear].data=u;
    qu[rear].parent=-1;
    visited[u]=1;
    while (front!=rear)         //隊不空循環
    {
        front++;                //出隊頂點w
        w=qu[front].data;
        if (w==v)               //找到v時輸出路徑之逆並退出
        {
            i=front;            //通過隊列輸出逆路徑
            while (qu[i].parent!=-1)
            {
                printf("%2d ",qu[i].data);
                i=qu[i].parent;
            }
            printf("%2d\n",qu[i].data);
            break;
        }
        p=G->adjlist[w].firstarc;   //找w的第一個鄰接點
        while (p!=NULL)
        {
            if (visited[p->adjvex]==0)
            {
                visited[p->adjvex]=1;
                rear++;             //將w的未訪問過的鄰接點進隊
                qu[rear].data=p->adjvex;
                qu[rear].parent=front;
            }
            p=p->nextarc;           //找w的下一個鄰接點
        }
    }
}

int main()
{
    ALGraph *G;
    int A[9][9]=
    {
        {0,1,1,0,0,0,0,0,0},
        {0,0,0,1,1,0,0,0,0},
        {0,0,0,0,1,1,0,0,0},
        {0,0,0,0,0,0,1,0,0},
        {0,0,0,0,0,1,1,0,0},
        {0,0,0,0,0,0,0,1,0},
        {0,0,0,0,0,0,0,1,1},
        {0,0,0,0,0,0,0,0,1},
        {0,0,0,0,0,0,0,0,0}
    };  //請畫出對應的有向圖
    ArrayToList(A[0], 9, G);
    ShortPath(G,0,7);
    return 0;
}


運行結果:

(7)最遠頂點
問題:求不帶權連通圖G中,距離頂點v最遠的頂點k

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

int Maxdist(ALGraph *G,int v)
{
    ArcNode *p;
    int i,j,k;
    int Qu[MAXV];               //環形隊列
    int visited[MAXV];              //訪問標記數組
    int front=0,rear=0;             //隊列的頭、尾指針
    for (i=0; i<G->n; i++)          //初始化訪問標誌數組
        visited[i]=0;
    rear++;
    Qu[rear]=v;                 //頂點v進隊
    visited[v]=1;               //標記v已訪問
    while (rear!=front)
    {
        front=(front+1)%MAXV;
        k=Qu[front];                //頂點k出隊
        p=G->adjlist[k].firstarc;       //找第一個鄰接點
        while (p!=NULL)             //所有未訪問過的相鄰點進隊
        {
            j=p->adjvex;            //鄰接點爲頂點j
            if (visited[j]==0)          //若j未訪問過
            {
                visited[j]=1;
                rear=(rear+1)%MAXV;
                Qu[rear]=j; //進隊
            }
            p=p->nextarc;           //找下一個鄰接點
        }
    }
    return k;
}

int main()
{
    ALGraph *G;
    int A[9][9]=
    {
        {0,1,1,0,0,0,0,0,0},
        {0,0,0,1,1,0,0,0,0},
        {0,0,0,0,1,1,0,0,0},
        {0,0,0,0,0,0,1,0,0},
        {0,0,0,0,0,1,1,0,0},
        {0,0,0,0,0,0,0,1,0},
        {0,0,0,0,0,0,0,1,1},
        {0,0,0,0,0,0,0,0,1},
        {0,0,0,0,0,0,0,0,0}
    };  //請畫出對應的有向圖
    ArrayToList(A[0], 9, G);
    printf("離頂點0最遠的頂點:%d",Maxdist(G,0));
    return 0;
}


運行結果:

 

 

 

 

 

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