关于数据结构:构造无向图及深度优先遍历连通图邻接矩阵递归

46次阅读

共计 936 个字符,预计需要花费 3 分钟才能阅读完成。

#include <iostream>
using namespace std;
#define MVNum 100                            
typedef char VerTexType;                    
typedef int ArcType;                     
typedef struct{VerTexType vexs[MVNum];                
    ArcType arcs[MVNum][MVNum];              
    int vexnum,arcnum;                        
}Graph;
bool visited[MVNum];                       
int LocateVex(Graph G , VerTexType v){for(int i = 0; i < G.vexnum; ++i)
        if(G.vexs[i] == v)
            return i;
        return -1;
}
// 创立无向图 
void CreateUDG(Graph &G){ 
    int i , j , k;
    cout <<"总顶点数 总边数:";
    cin >> G.vexnum >> G.arcnum;                            
    for(i = 0; i < G.vexnum; ++i){cout << "第" << (i+1) << "个点的名称:";
        cin >> G.vexs[i];                                
    }    
    for(i = 0; i < G.vexnum; ++i)                            
        for(j = 0; j < G.vexnum; ++j)   
            G.arcs[i][j] = 0;  
    for(k = 0; k < G.arcnum;++k){                        
        VerTexType v1 , v2;
        cout << "第" << (k + 1) << "条边附丽的顶点:";
        cin >> v1 >> v2;                                    
        i = LocateVex(G, v1);  j = LocateVex(G, v2);        
        G.arcs[j][i] = G.arcs[i][j] = 1;                
    }
}
// 深度优先遍历 
void DFS(Graph G, int v){                
    int w;
    cout << G.vexs[v];  visited[v] = true;          
    for(w = 0; w < G.vexnum; w++)                           
        if((G.arcs[v][w] != 0)&& (!visited[w]))  DFS(G, w); 
}
int main(){
    Graph G;
    CreateUDG(G);
    cout << "遍历无向图的起始点:";
    VerTexType c;
    cin >> c;
    int i;
    for(i = 0 ; i < G.vexnum ; ++i){if(c == G.vexs[i])
            break;
    }
    cout << "深度优先遍历无向图:";
    DFS(G , i);
    return 0;
}

正文完
 0