c++图的广度优先遍历和深度优先遍历

本文介绍了如何使用C++实现图的两种遍历方式:宽度优先搜索(BFS)和深度优先搜索(DFS)。通过BFS.h、DFS.h、Graph.h、Graph.cpp和main.cpp五个文件来实现相关算法,分别展示了BFS和DFS的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BFS.h

#pragma once
//广度优先遍历
#include"Graph.h"
#include<queue>
#include<iostream>
vector<Node*>BFS(Graph graph, int start)
{
       vector<Node*>res;
       unordered_set<Node*>marked;//标记集合
       queue<Node*>que;
       //将起始点放入到队列中并且添加标记
       que.push(graph.nodes[start]);
       marked.insert(graph.nodes[start]);
       while (!que.empty())
       {
              //弹出队列的首元素并且放入结果集中或者直接打印
              Node* front = que.front();
              que.pop();
              cout << (char)front->val << " ";
              res.push_back(front);
              for (int i = 0; i < front->next.size(); i++)
              {
                     if (marked.find(front->next[i]) == marked.end())
                     {
                           que.push(front->next[i]);
                           marked.insert(front->next[i]);
                     }
        
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值