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

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

程序员文章站 2022-06-13 11:37:33
...
#include <iostream>
#include <malloc.h>
#include <queue>

#define NumVertex 20

bool visited[NumVertex];
using namespace std;

typedef struct node{
    int adjvex;
    node *next;
}EgdeNode;

typedef struct{
    int vertex;
    EgdeNode *firstedge;
}VertexNode;
typedef struct{
    VertexNode vexlist[NumVertex];
    int n,e;
}AdjGraph;

void CreateGraph(AdjGraph *G){
    int i,head,tail;
    cout << "请输入顶点数和边数:" << endl;
    cin >> G->n >> G->e ;
    cout << "请输入顶点信息:" << endl;
    for( i=0 ; i < G->n ; i++ ){
        cin >> G->vexlist[i].vertex ;
        G->vexlist[i].firstedge = NULL ;
    }
    for( i=0 ; i < G->e ; i++ ){
        cout << "请输入边(i, j)的上标,下标:" << endl;
        cin >> tail >> head ;
        EgdeNode * p = (EgdeNode *)malloc(sizeof(node));
        p -> adjvex = head;
        p -> next = G->vexlist[tail].firstedge;
        G->vexlist[tail].firstedge = p;
        EgdeNode * q = (EgdeNode *)malloc(sizeof(node));
        q -> adjvex = tail;
        q -> next = G->vexlist[head].firstedge;
        G->vexlist[head].firstedge = q;
    }
}

/*void ShowView(AdjGraph *G){
    int i;
    for( i=0 ; i< G->n ; i++){
        EgdeNode * p = (EgdeNode *)malloc(sizeof(node));
        cout << G->vexlist[i].vertex <<" ";
        p = G->vexlist[i].firstedge;
        while(p){
            cout << p->adjvex <<" ";
        }
        cout<<endl;
    }
}*/
void DFS(AdjGraph *G , int i){
    EgdeNode * p = (EgdeNode *)malloc(sizeof(node));
    cout << G->vexlist[i].vertex <<" ";
    visited[i] = true;
    p = G->vexlist[i].firstedge;
    while(p){
        if( !visited[p->adjvex] )  DFS(G,p->adjvex);
        p = p->next;
    }
}

void DFSTraverse(AdjGraph *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(AdjGraph *G , int i){
    queue <int> Q;
    EgdeNode * p = (EgdeNode *)malloc(sizeof(node));
    cout << G->vexlist[i].vertex <<" ";
    visited[i] = true;
    Q.push(i);
    while( !Q.empty() ){
        i = Q.front();
        Q.pop();
        p = G->vexlist[i].firstedge;
        while(p){
            if( !visited[p->adjvex] ){
                cout << G->vexlist[p->adjvex].vertex << " ";
                visited[p->adjvex] = true ;
                Q.push(p->adjvex);
            }
            p = p->next;
        }
    }
}

void BFSTraverse(AdjGraph *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()
{
    AdjGraph G;
    CreateGraph(&G);
//    ShowView(&G);
    cout<<"深度优先遍历:";
    DFSTraverse(&G);
    cout<<endl;
    cout<<"广度优先遍历:";
    BFSTraverse(&G);
    return 0;
}

 

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