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

图的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();
    }
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SweetCode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值