#include<bits/stdc++.h>
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 FirstAdjVex(Graph G , int v){
int i;
for(i = 0 ; i < G.vexnum ; ++i){
if(G.arcs[v][i] == 1 && visited[i] == false)
return i;}
return -1;
}
int NextAdjVex(Graph G , int v , int w){
int i;for(i = w ; i < G.vexnum ; ++i){
if(G.arcs[v][i] == 1 && visited[i] == false)return i;}
return -1;
}
int LocateVex(Graph G , VerTexType v){
//确定点在G中的位置
for(int i = 0; i <G.vexnum; ++i)
if(G.vexs[i]==v)
return i;
return -1;
}//LocateVex
void CreateUDN(Graph &G){
//采用邻接矩阵表孟法创建无向网G
int i , j , k;
cout <<"请输入总顶点数,总边数,以空格隔开:";
cin >> G.vexnum >> G.arcnum;
cout << endl;
cout <<"输入点的名称,如a" << endl;
for(i = 0; i < G.vexnum; ++i){
cout <<"请输入第" << (i+1) <<"个点的名称:";
cin >> G.vexs[i];
}
cout << endl;
for(i = 0; i < G.vexnum; ++i)
for(j = 0; j < G.vexnum; ++j)
G.arcs[i][j] = 0;
cout <<"输入边依附的顶点,如a b" << endl;
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){
cout << G.vexs[v] <<" ";visited[v] = true;
int w;
for(w = FirstAdjVex(G, v);w>=0;w = NextAdjVex(G,v,w))
if(!visited[w]) DFS(G, w);
}
void DFSTraverse(Graph G){
int v;
for(v = 0; v < G.vexnum; ++v)
visited[v] = false;
for(v = 0; v < G.vexnum; ++v)
if(!visited[v]) DFS(G, v);
}
int main(){
cout <<"************深度优先搜索遍历非连通图**************"<<endl << endl;
Graph G;
CreateUDN(G);
cout << endl;
cout<<"无向图G创建完成!" << endl << endl;
cout << "深度优先搜索遍历非连通图结果:" << endl;
DFSTraverse(G);
cout <<endl;
return 0;
}
数据结构c++:深度优先搜索连通图
最新推荐文章于 2024-08-31 22:19:14 发布