1. 程式人生 > >資料結構 圖的優先遍歷(鄰接矩陣)

資料結構 圖的優先遍歷(鄰接矩陣)

資料結構

#include <iostream>     
using namespace std;
   
#define maxsizes 105
typedef int Type;

// 頂點定義
typedef struct{
    Type data;
}vertex;

// 鄰接矩陣定義
typedef struct{ 
    int n,e;
    vertex vex[maxsizes];
    int edges[maxsizes][maxsizes];
}MGraph;

// 訪問結點
void visitvertex(MGraph G,int x){
    cout<<" "<<x;//G.vex[x].data;
}

// 深度優先遍歷
bool visit[maxsizes]={false};
void DFS(MGraph &G,int v){
    visit[v]=true;
    visitvertex(G,v); 

    for(int i=1;i<=G.n;++i){
        if(visit[i]==false && G.edges[v][i]==1){
            DFS(G,i);
        }
    } 
}

/*
7 7
1 2 
1 3
3 6
2 5
5 4 
5 7 
4 7
//  1 2 5 4 7 3 6
*/
// 圖的深度優先遍歷演算法 (鄰接矩陣)
int main(void){     
    MGraph G;
    cin>>G.n>>G.e;

    for(int i=1;i<=G.e;++i){    // 鄰接矩陣 
        int temp1,temp2;
        cin>>temp1>>temp2;
        G.edges[temp1][temp2]=1; // 無向圖
        G.edges[temp2][temp1]=1;
    } 
       
    for(int j=1;j<=G.n;++j){
        if(visit[j]==false){
            DFS(G,j); 
        }
    }  

    return 0;
} // jinzheng 2018.9.19 20:00