- #include<iostream>
- #include<stdlib.h>
- #include<queue>
- using namespace std;
- #define OK 1
- #define OVERFLOW -2
- typedef int Status;
- typedef char VertexType;
- typedef enum{DG,DN,UDG,UDM} GraphKind;
- typedef struct ArcNode{
- int adjvex;
- struct ArcNode *nextarc;
- }ArcNode;
- typedef struct VNode{
- VertexType data;
- ArcNode *firstarc;
- }VNode,*AdjList;
- typedef struct {
- AdjList vertices;
- int vexnum,arcnum;
- GraphKind kind;
- }ALGraph;
- typedef Status (*Visit)(ALGraph G,int v);
- int LocateVex(ALGraph G,VertexType v)
- {
- for(int i=0;i<G.vexnum;i++)
- if(G.vertices[i].data==v) return i;
- return G.vexnum;}
- Status CreateUDG(ALGraph &G)
- {
- G.kind=UDG; //无向图
- cin>>G.vexnum>>G.arcnum;
- if(!(G.vertices=new VNode[G.vexnum])) exit(OVERFLOW);
- for(int i=0;i<G.vexnum;i++) {
- cin>>G.vertices[i].data;
- G.vertices[i].firstarc=NULL;}
- VertexType v1,v2;
- ArcNode *p,*q;
- int i,j,k=0;
- for(;k<G.arcnum;k++) {
- do
- {
- cin>>v1>>v2;
- i=LocateVex(G,v1);
- j=LocateVex(G,v2);
- }while(i==G.vexnum||j==G.vexnum);
- p=new ArcNode;
- q=new ArcNode;
- if(!p||!q) exit(OVERFLOW);
- p->adjvex=j;
- p->nextarc=G.vertices[i].firstarc;
- G.vertices[i].firstarc=p;
- q->adjvex=i;
- q->nextarc=G.vertices[j].firstarc;
- G.vertices[j].firstarc=q;
- }
- return OK;
- }
- Status Print(ALGraph G,int v){
- cout<<G.vertices[v].data<<" ";
- return OK; }
- Visit vis=Print;
- void DFS(ALGraph G,int v,bool *&visited);
- void DFSTraverse(ALGraph G){
- bool *visited=new bool[G.vexnum];
- if(!visited) exit(OVERFLOW);
- int i=0;
- for(;i<G.vexnum;i++)
- visited[i]=false;
- for(i=0;i<G.vexnum;i++)
- if(!visited[i]) DFS(G,i,visited);
- cout<<endl;}
- void DFS(ALGraph G,int v,bool *(&visited)){
- visited[v]=true;
- vis(G,v);
- for(ArcNode* w=G.vertices[v].firstarc;w;w=w->nextarc)
- if(!visited[w->adjvex])
- DFS(G,w->adjvex,visited);}
- void BFSTraverse(ALGraph G){
- bool *visited=new bool[G.vexnum];
- if(!visited) exit(OVERFLOW);
- queue<int> q;
- int i=0,v;
- for(;i<G.vexnum;i++)
- visited[i]=false;
- for(i=0;i<G.vexnum;i++){
- if(!visited[i]){
- visited[i]=true;
- vis(G,i);
- q.push(i);
- while(!q.empty()){
- v=q.front();
- q.pop();
- for(ArcNode* w=G.vertices[v].firstarc;w;w=w->nextarc)
- if(!visited[w->adjvex]){
- visited[w->adjvex]=true;
- vis(G,w->adjvex);
- q.push(w->adjvex);}
- }
- }
- }
- cout<<endl;
- }
- int main()
- {
- ALGraph G;
- CreateUDG(G);
- DFSTraverse(G);
- BFSTraverse(G);
- return 0;}
- 输入:
- 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
- 输出:
- a c g f b e h d
- a c b g f e d h
- 请按任意键继续. . .