#include <iostream> #include <cstdlib> #define INF 99999999 using namespace std; #define MaxVnum 50 //图的顶点数上限 typedef struct ArcNode{//表结点 int adjvex; struct ArcNode *nextarc; //第一种 void set(ArcNode *s1,ArcNode *s2){ s1->adjvex=s2->adjvex; s1->nextarc=s2->nextarc; } ArcNode& operator=(const ArcNode *a){ set(this,(ArcNode *)&a); } /*第二种 ArcNode& operator=(ArcNode& a){ adjvex=a.adjvex; nextarc=a.nextarc; return *this; } 类似与第二种 ArcNode* operator=(ArcNode* a){ adjvex=a->adjvex; nextarc=a->nextarc; return this; } */ }ArcNode; typedef struct{//头结点 ArcNode *firstarc; }AdjList[MaxVnum]; typedef struct{ int vexnum,arcnum;//图的实际顶点数、边数 AdjList vertices;//邻接表 }ALGraph; bool visited[MaxVnum];//访问标志数组 void Create_ALGraph(ALGraph &G); void DFSTraverse_ALGraph(ALGraph G); void DFS_ALGraph(ALGraph G,int v); int main(){ ALGraph G2; Create_ALGraph(G2); DFSTraverse_ALGraph(G2); return 0; } void Create_ALGraph(ALGraph &G){ cin>>G.vexnum>>G.arcnum; for(int i=0;i<G.vexnum;i++) G.vertices[i].firstarc=NULL; for(int i=0;i<G.vexnum;i++){ char a[G.vexnum+1]; cin>>a; for(int j=0;j<G.vexnum;j++) if(a[j]=='1'){ ArcNode *p; p=(ArcNode *)malloc(sizeof(ArcNode)); p->adjvex=j;p->nextarc=NULL; ArcNode *q=G.vertices[i].firstarc; if(!q){ q=p;//想要实现这个 } else{ while(q->nextarc)q=q->nextarc; q->nextarc=p; } } } } void DFSTraverse_ALGraph(ALGraph G){ for(int v=0;v<G.vexnum;v++) visited[v]=false; for(int v=0;v<G.vexnum;v++) if(!visited[v]) DFS_ALGraph(G,v); } void DFS_ALGraph(ALGraph G,int v){ visited[v]=true; cout<<v<<endl; for(ArcNode *w=G.vertices[v].firstarc;w;w=w->nextarc){ int p=w->adjvex; if(!visited[p]) DFS_ALGraph(G,p); } }
onemoo
mrs_empress
相关分类