【非递归实现 BFS】 + 栈

本文探讨了一种非递归方法来实现宽度优先搜索(BFS),通过利用栈的数据结构,有效地遍历图或树节点,避免了递归带来的额外开销。详细介绍了算法步骤并提供了代码示例。
摘要由CSDN通过智能技术生成

代码:

#include<iostream>
using namespace std;
int vis[110];
struct node{
    int a;
    node *next;
};
typedef struct node1{
    char s;
    node *f;
}st[110];
struct node2{
   st ss;
   int vn,vm;
};
struct sta{
    int *s;
    int f,e;
};
void Bsta(sta &S){
    S.s = new int[110];
    S.f = S.e = 0;
}
void Ista(sta &S,int a){
    if((S.e + 1) % 110 == S.f) return ;
    S.e = (S.e + 1) % 110;
    S.s[S.e] = a;
}
bool Esta(sta &S){
    if(S.f == S.e) return true;
    return false;
}
int Dsta(sta &S){
    int a = S.s[S.e--];
    return a;
}
int w(node2 G,char s){
    for(int i = 1; i <= G.vn; i++)
        if(G.ss[i].s == s)
            return i;
}
void bd(node2 &G){
     cout << "输入总的顶点数和边数" << endl;
     cin >> G.vn >> G.vm;
     cout << "依次输入顶点名称" << endl;
     for(int i = 1; i <= G.vn; i++)
        cout << "第" << i << "顶点的名称是" << endl,cin >> G.ss[i].s,G.ss[i].f = NULL;
     cout << "依次输入每条边连接的两个点" << endl;
     for(int i = 1; i <= G.vm; i++){
        char a,b;
        cout << "\n第" << i << "条边连接两个点为";
        cin >> a >> b;
        int ma = w(G,a),mb = w(G,b);
        node *p = new node;
        p -> a = mb;
        p -> next = G.ss[ma].f;
        G.ss[ma].f = p;
        p = new node;
        p -> a = ma;
        p -> next = G.ss[mb].f;
        G.ss[mb].f = p;
     }
}
void BFS(node2 G,int a){
    sta S;
    cout << G.ss[a].s << " ";
    Bsta(S);
    Ista(S,a);
    while(!Esta(S)){
        int o = Dsta(S);
        node *p = G.ss[o].f;
        int ok = 0;
        while(p && vis[p -> a]) p = p -> next;
        if(!p) continue;
        int b = p -> a;
        p = p -> next;
       if(p)
            Ista(S,o),G.ss[o].f = p;
                cout << G.ss[b].s << " ",vis[b] = 1,Ista(S,b);
    }
}
int main(){
    node2 G;
    bd(G);
    cout << "输入合法起点" << endl;
    char c;
    cin >> c;
    int mc = w(G,c);
    cout << "BFS遍历结果" << endl;
    vis[mc] = 1;
    BFS(G,mc);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值