图的DFS非递归遍历完整算法(可直接测试)

发布于:2022-12-31 ⋅ 阅读:(589) ⋅ 点赞:(0)

图的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;
    }
}

//DFS
void DFS(ALGraph g);
void dfs(ALGraph graph,Vnode g);

/*
 * 测试样例
 4 5
 1 2
 1 3
 2 3
 2 4
 3 4
 */

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();
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到