广度遍历有向图

问题:还是指针的问题,在第一次遍历时,一定要用一个临时指针来指向图节点,不然等遍历玩指针为空,再用广度遍历算法就会失效。

广度遍历类似于树层次遍历,只是有顺序,因此用到了队列。再次证明了STL的强大和方便。

代码:

#include <iostream>
#include <cstdlib>
#include <queue>
using namespace std;
 
#define MAXV 20
 
typedef struct edgeNode
{
    int data;
    struct edgeNode *next;
}edgeList;
 
typedef struct headNode
{
    char vex;
    edgeList *firstNode;
}headList;
 
typedef struct graph           //定义邻接表结构
{
    headList arr[MAXV];
    int v,e;
}*adjGraph;
 
 
void createAdjGraph(adjGraph &ag)
{
    char c;
    int p,q;
    edgeList *s;
    cout<<"please input the num of v and e:";
    cin>>ag->v>>ag->e;
 
    for(int i=0;i<ag->v;i++)             //初始化头节点
    {
        cout<<"please input vex:";
        cin>>c;
        ag->arr[i].vex=c;
        ag->arr[i].firstNode=NULL;
    }
 
    for(int j=0;j<ag->e;j++)
    {
        cout<<"please input two vexs:";
        cin>>p>>q;
        s=(edgeList *)malloc(sizeof(struct edgeNode));
        s->data=p;
        s->next=ag->arr[q].firstNode;
        ag->arr[q].firstNode=s;
    }
}
 
void showAdjGraph(adjGraph ag)
{
    edgeList* s;
    for(int i=0;i<ag->v;i++)
    {
        cout<<ag->arr[i].vex<<"  ";
        s=ag->arr[i].firstNode;
        while(s!=NULL)
        {
            cout<<s->data<<" ";
            s=s->next;
        }
        cout<<endl;
    }
    delete s;
}
 
void BFSTraveral(adjGraph ag)
{
    int visited[MAXV];
    int k;
    queue<int> q;
    edgeList *el;
    el=(edgeList*)malloc(sizeof(struct edgeNode));
 
    for(int i=0;i<ag->v;i++)
    {
        visited[i]=0;
    }
 
    for(int i=0;i<ag->v;i++)
    {
        if(visited[i]==0)
        {      
        visited[i]=1;
        cout<<ag->arr[i].vex<<"->";
        q.push(i);
        while(!q.empty())  
        {
             k=q.front();  
             q.pop();
             el=ag->arr[k].firstNode;
            // cout<<"hello world";
             while(el)
             {  
              // cout<<"hello world";
              if(visited[el->data]==0)
              {
                  visited[el->data]=1;
                  cout<<ag->arr[el->data].vex<<"->";
            //    cout<<"hello world";
                  q.push(el->data);
              }
              el=el->next;
               
             }
             cout<<endl;
        }
        }
         
    }
    free(el);
}
 
 
int main()
{
    adjGraph ag;
    ag=(adjGraph)malloc(sizeof(struct graph));
    cout<<"创建有向图:"<<endl;
    createAdjGraph(ag);
    cout<<"输出有向图"<<endl;
    showAdjGraph(ag);
    cout<<"广度遍历有向图:"<<endl;
    BFSTraveral(ag);
    return 0;
}

 运行截图:

posted @   xshang  阅读(540)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示