#include <iostream> #include <stack> using namespace std; #define MVNum 100 typedef int OtherInfo; typedef string VerTexType; typedef struct ArcNode { int adjvex; struct ArcNode * nextarc; OtherInfo info; }ArcNode; typedef struct VNode { VerTexType data; ArcNode *firstarc; }VNode,AdjList[MVNum]; typedef struct { AdjList vertices; int vexnum,arcnum; }ALGraph; int LocateVex(ALGraph G,VerTexType v) { int i; for(i=0;i<G.vexnum;i++) { if(G.vertices[i].data==v) return i; } return -1; } int CreateUDG(ALGraph &G) { int i,j,k; VerTexType v1,v2; ArcNode *p,*p2; cin>>G.vexnum>>G.arcnum; for(i=0;i<G.vexnum;i++) { cin>>G.vertices[i].data; G.vertices[i].firstarc=NULL; } for(k=0;k<G.arcnum;k++) { cin>>v1>>v2; i=LocateVex(G,v1); j=LocateVex(G,v2); p=new ArcNode; p->adjvex=j; p->nextarc=G.vertices[i].firstarc; G.vertices[i].firstarc=p; p2=new ArcNode; p2->adjvex=i; p2->nextarc=G.vertices[j].firstarc; G.vertices[j].firstarc=p2; } return 1; } void DFS_AL2(ALGraph G) { bool visited[MVNum]={false}; stack<int> S; cout<<G.vertices[0].data<<" "; visited[0]=true; S.push(0); ArcNode *p; while(!S.empty()) { p=G.vertices[S.top()].firstarc; while(p&&visited[p->adjvex])//选择 { p=p->nextarc; } while(p&&!visited[p->adjvex])//走这个方向 { cout<<G.vertices[p->adjvex].data<<" "; visited[p->adjvex]=true; S.push(p->adjvex); p=G.vertices[p->adjvex].firstarc; } if(p==NULL) { S.pop(); } } } int main() { ALGraph G; CreateUDG(G); DFS_AL2(G); }
邻接表存储的无向图非递归深度优先遍历算法
猜你喜欢
转载自blog.csdn.net/Pamkuu/article/details/80723526
今日推荐
周排行