图的DFS非递归遍历完整算法
- 相关图的邻接表的理论和遍历的思路大家可以自行查阅
- 自主学习能力也很重要,每个人的时间都很有限,在此仅讲实践
#include <iostream>
#include <stdio.h>
#include <stack>
#define null NULL
#define max_n 101
using namespace std;
typedef int vexType;
int visited[max_n];
typedef struct arcnode{
vexType vexid;
struct arcnode *nextarc;
}ArcNode,Vnode,vexList[max_n];
typedef struct {
int vexnum,edgenum;
vexList vexs;
}ALGraph;
void clear_visited(){
fill(visited,visited+max_n,false);
}
void init_g(ALGraph &g){
for(int i=0;i<=g.vexnum;i++){
g.vexs[i].vexid=i;
g.vexs[i].nextarc=null;
}
}
void show_g(ALGraph g){
for(int i=1;i<=g.vexnum;i++){
cout<<g.vexs[i].vexid<<"->";
ArcNode *p=g.vexs[i].nextarc;
while(p){
cout<<p->vexid<<"-";
p=p->nextarc;
}
cout<<"^"<<endl;
}
}
void DFS(ALGraph g);
void dfs(ALGraph graph,Vnode g);
int main() {
ALGraph graph;
int m,n,u,v;
cin>>n>>m;
graph.vexnum=n;
graph.edgenum=m;
init_g(graph);
for(int i=0;i<m;i++){
cin>>u>>v;
ArcNode *p=(ArcNode *)malloc(sizeof(ArcNode));
ArcNode *q=(ArcNode *)malloc(sizeof(ArcNode));
p->vexid=u; p->nextarc=null;
q->vexid=v; q->nextarc=null;
p->nextarc=graph.vexs[v].nextarc;
graph.vexs[v].nextarc=p;
q->nextarc=graph.vexs[u].nextarc;
graph.vexs[u].nextarc=q;
}
show_g(graph);
DFS(graph);
return 0;
}
void DFS(ALGraph g){
clear_visited();
for(int i=1;i<=g.vexnum;i++){
if(!visited[i]){
dfs(g,g.vexs[i]);
}
}
}
void dfs(ALGraph graph,Vnode g){
stack<int> st;
st.push(g.vexid);
printf("%d ",g.vexid);
visited[g.vexid]=true;
while(!st.empty()){
int id=st.top();
if(!visited[id]) {
visited[id]= true;
printf("%d ",id);
}
ArcNode *p=graph.vexs[id].nextarc;
while (p){
if(!visited[p->vexid]){
st.push(p->vexid);
break;
}
p=p->nextarc;
}
if(!p) st.pop();
}
}