欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

无向图的邻接矩阵遍历:深度优先搜索+广度优先搜索

程序员文章站 2022-03-14 10:11:05
...
#include <iostream>
#include <queue>

#define NumVertices 20

bool visited[NumVertices];
int dfn[NumVertices];

using namespace std;

typedef struct{
    int vertex[NumVertices];
    int edge[NumVertices][NumVertices];
    int n,e;
}MTGraph;

void CreateMTGraph(MTGraph *G){
    cout << "请输入顶点数和边数:" << endl;
    cin >> G->n >> G->e;
    int i,j,k;
    cout << "请输入顶点信息:" << endl;
    for(i = 0; i < G->n ; i++)
        cin >> G->vertex[i];
    for(i = 0 ; i < G->e ; i++){
        for(j = 0; j < G->e ; j++){
            G->edge[i][j] = 0;
        }
    }
    for(k = 0;k < G->e ; k++){
        cout << "请输入边(i, j)的上标,下标:" << endl;
        cin >> i >> j;
        G->edge[i][j] = 1;
        G->edge[j][i] = 1;
    }
}

void ShowView(MTGraph *G){
    int i,j;
    for( i=0 ; i< G->n ; i++){
        for(j=0;j < G->n ; j++){
            cout<<G->edge[i][j]<<" ";
        }
        cout<<endl;
    }
}

void DFS(MTGraph *G,int i){
    int j;
    cout<< G->vertex[i] <<" ";
    visited[i]= true;
    for(j = 0;j < G->n ;j++){
        if ( (G->edge[i][j]==1) && (!visited[j]) )
            DFS(G,j);
    }
}

void DFSTraverse( MTGraph *G){
    int i;
    for(i = 0;i < G->n ;i++)
        visited[i] = false;
    for(i = 0;i < G->n ;i++)
        if(!visited[i])  DFS(G,i);
}

void BFS(MTGraph *G,int i){
    queue <int> q;
    int j;
    cout<<G->vertex[i]<<" ";
    visited[i]= true;
    q.push(i);
    while(!q.empty()){
        i = q.front();
        q.pop();
        for(j = 0;j < G->n ;j++){
            if ( (G->edge[i][j]==1) && (!visited[j]) ){
                cout<<G->vertex[j]<<" ";
                visited[j]= true;
                q.push(j);
            }
        }
    }
}

void BFSTraverse(MTGraph *G){
    int i;
    for(i = 0;i < G->n ;i++)
        visited[i] = false;
    for(i = 0;i < G->n ;i++)
        if(!visited[i])  BFS(G,i);
}


int main()
{
    MTGraph G;
    CreateMTGraph(&G);
    ShowView(&G);
    cout<<"深度优先遍历:";
    DFSTraverse(&G);
    cout<<endl;
    cout<<"广度优先遍历:";
    BFSTraverse(&G);

}

无向图的邻接矩阵遍历:深度优先搜索+广度优先搜索