网上找的一个图,对这个图进行dfs
/*************************************************************************
> File Name: adjlist.cpp
> Author:gens_ukiy
> Mail:
> Created Time: 2016年11月29日 星期二 07时22分40秒
************************************************************************/
#include<iostream>
#include<vector>
//#include<set>
#include<map>
#include<cstdio>
using namespace std;
#define MAX_N 200
#define inf 0x3f3f3f
typedef struct {
vector<int> arcs[MAX_N];//每个顶点的表
char vex[MAX_N];//顶点信息
int vexnum;//顶点数
int arcnum;//边数
map<char,int> bar;
map<int,char> foo;
}Adjlist;
void Create(Adjlist *G){
//printf("vexnum:\n");
cin>>G->vexnum;
//printf("arcnum:\n");
cin>>G->arcnum;
for(int i=1;i<=G->vexnum;i++){
cin>>G->vex[i]; // A B C D E F 之类的节点
G->bar[G->vex[i]]=i;
G->foo[i]=G->vex[i];
}
for(int i=1;i<=G->arcnum;i++){
char vex1,vex2;
cin>>vex1>>vex2;
G->arcs[G->bar[vex1]].push_back(G->bar[vex2]);
G->arcs[G->bar[vex2]].push_back(G->bar[vex1]);
}
printf("bar:\n");
for(int i=1;i<=G->vexnum;i++){
printf("%c ",G->foo[i]);
}
printf("\n");
printf("adjlist :\n");
for(int i=1;i<=G->vexnum;i++){
printf("%c ------>",G->vex[i]);
for(vector<int>::iterator j=G->arcs[i].begin();j!=G->arcs[i].end();j++){
printf("%c ",G->foo[*j]);
}
printf("\n");
}
}
int vis[MAX_N]={0};
vector<int>::iterator FirstAdjVex(Adjlist g,int v0);
vector<int>::iterator NextAdjVex(Adjlist g,int v0,vector<int>::iterator w);
void dfs(Adjlist g,int v0){
cout<<g.foo[v0]<<" ";
vis[v0]=1;
vector<int>::iterator w;
if(!g.arcs[v0].empty())
w=g.arcs[v0].begin();
else
w=g.arcs[v0].end();
while(w!=g.arcs[v0].end()){
if(!vis[*w]){
dfs(g,*w);
}
w++;
}
return;
}
vector<int>::iterator FirstAdjVex(Adjlist g,int v0){
return g.arcs[v0].begin();
}
vector<int>::iterator NextAdjVex(Adjlist g,int v0,vector<int>::iterator w){
return ++w;
}
void TraverseG(Adjlist g){
printf("traversal graph :\n");
for(int i=1;i<=g.vexnum;i++){
vis[i]=0;
}
for(int v=1;v<=g.vexnum;v++){
if(!vis[v]){
dfs(g,v);
}
}
}
int main(){
//freopen("in5.txt","r",stdin);
//freopen("out.txt","w",stdout);
Adjlist G;
Create(&G);
TraverseG(G);
return 0;
}
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
E H
F G
out.txt
bar:
A B C D E F G H
adjlist :
A ------>B C
B ------>A D E
C ------>A F G
D ------>B H
E ------>B H
F ------>C G
G ------>C F
H ------>D E
traversal graph :
A B D H E C F G