图的广度遍历(BFS)

#include <iostream>
#include <queue>
using namespace std;

typedef struct node 
{
    int nVertex;
    int nEdge;
    int *pMatrix;
}Graph;

Graph *CreateGraph()
{
    Graph *pGraph = NULL;
    pGraph = (Graph*)malloc(sizeof(Graph));

    printf("请输入顶点个数与边的个数:\n");
    int nV,nE;
    scanf("%d%d",&nV,&nE);
    pGraph->nVertex = nV;
    pGraph->nEdge = nE;

    //矩阵
    pGraph->pMatrix = (int*)malloc(sizeof(int)*nV*nV);
    memset(pGraph->pMatrix,0,sizeof(int)*nV*nV);

    //放入边
    int v1,v2;
    int i;
    for(i=0;i<nE;i++)
    {
        printf("请输入一条边:\n");
        scanf("%d%d",&v1,&v2);
        //确保该点符合范围要求,且该点没有被赋值过
        if(v1 != v2 && v1>=1 && v1 <= nV && v2>=1 && v2<=nV && pGraph->pMatrix[(v1-1)*nV+v2-1]==0)
        {
            pGraph->pMatrix[(v1-1)*nV+v2-1] = 1;
            pGraph->pMatrix[(v2-1)*nV+v1-1] = 1;
        }
        else
        {
            i--;
        }
    }
    return pGraph;
}

void BFS(Graph *pGraph,int nBegin)
{
    if(pGraph == NULL || nBegin<1 || nBegin>pGraph->nVertex)return;

    //队列
    queue<int>q;

    //标记数组
    int *pMark = NULL;
    pMark = (int*)malloc(sizeof(int)*pGraph->nVertex);
    memset(pMark,0,sizeof(int)*pGraph->nVertex);

    //起始顶点入队 标记
    q.push(nBegin);
    pMark[nBegin-1] = 1;

    //处理
    while(!q.empty())
    {
        nBegin = q.front();
        cout<<nBegin<<" ";
        q.pop();

        //遍历
        int i;
        for(i=0;i<pGraph->nVertex;i++)
        {
            //找到有关的且未被打印的
            if(pGraph->pMatrix[(nBegin-1)*pGraph->nVertex+i] == 1 && pMark[i] == 0)
            {
                //入队 进行标记
                q.push(i+1);
                pMark[i] = 1;
            }
        }
    }
    cout<<endl;

    //释放
    free(pMark);
    pMark = NULL;
}

int main()
{
    Graph *pGraph = CreateGraph();

    BFS(pGraph,2);
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值