还是这个图,对它用邻接矩阵dfs遍历
#include<bits/stdc++.h>
using namespace std;
#define MAXVEX 20
#define infinity 0x3f3f3f
typedef struct {
char arcs[MAXVEX][MAXVEX]; // 边信息
char vex[MAXVEX]; //顶点信息
int vexnum; //顶点数目
int arcnum; //边数目
map<char,int> bar;//A ->1 B ->2
map<int,char> foo;//1 ->A 2->B 就像英汉词典互译...
}AdjMatrix; //邻接矩阵
void Create(AdjMatrix *G){
int i,j,k,weight=1;
//printf("请输入无向网中的顶点数和边数:\n");
cin>>G->vexnum>>G->arcnum;
//index from [1 , G->vexnum]
for(int i = 1;i <= G->vexnum;i++){
for(int j = 1;j <= G->vexnum;j++){
G->arcs[i][j] = '\0';
}
}
//printf("请输入无向网中%d个顶点:\n",G->vexnum);
//index form [1 , G->vexnum];
for(int i = 1;i <=G->vexnum;i++){
//printf("No.%d个顶点:顶点V",i);
cin>>G->vex[i]; //A B C D 之类的顶点标识
G->bar[G->vex[i]]=i; // bar[B]=2;
G->foo[i]=G->vex[i]; // f[2] = B;
}
//printf("请输入无向无向网中%d条边:\n",G->arcnum);
for(int k=0;k<G->arcnum;k++){
//printf("\nNo.%d条边:\n 顶点V",k+1);
char vex1,vex2;
cin>>vex1;
//printf("<------->顶点V");
cin>>vex2;
/*
printf("权值: ");
cin>>weight;
*/
G->arcs[G->bar[vex1]][G->bar[vex2]] = weight; //如果不是网,则赋值1
G->arcs[G->bar[vex2]][G->bar[vex1]] = weight; //如果是有向图,删掉此句
}
}
int visit[MAXVEX]={0};
int FirstAdjVex(AdjMatrix g,int v0);
int NextAdjVex(AdjMatrix g,int v0,int w);
void dfs(AdjMatrix g,int v0){
cout<<g.foo[v0];
visit[v0] = 1;
int w = FirstAdjVex(g,v0); // v0的第一个邻接点
while(w != -1){
if(!visit[w]){
dfs(g,w);
}
w = NextAdjVex(g,v0,w); // v0的下一个邻接点
}
}
void TraverseG(AdjMatrix g){
for(int v = 1;v <= g.vexnum; v++){
visit[v] = 0;
}
for(int v = 1;v <= g.vexnum; v++){
if(!visit[v]){
dfs(g,v);
}
}
}
int FirstAdjVex(AdjMatrix g,int v0){
int i;
for(i = 1;i <= g.vexnum;i++){
if(g.arcs[v0][i] !='\0'){
break;
}
}
if(i <= g.vexnum)
return i;
else
return -1;
}
int NextAdjVex(AdjMatrix g,int v0,int w){
int i=w+1;
for(;i <= g.vexnum; i++){
if(g.arcs[v0][i] != '\0'){
break;
}
}
if(i <= g.vexnum)
return i;
else
return -1;
}
int main(){
//freopen("in5.txt","r",stdin);
//freopen("out.txt","w",stdout);
AdjMatrix G;
Create(&G);
TraverseG(G);
}
in5.txt
8 9
A B C D E F G H
A B
A C
B D
B E
C F
C G
D H
F G
out.txt
A B D H E C F G