c++实现广度优先搜索

以下是一个简单的C++程序示例,用于实现广度优先搜索(BFS)算法:

cpp 复制代码
#include <iostream>
#include <list>
#include <queue>

using namespace std;

class Graph {
    int numVertices;
    list<int> *adjLists;

public:
    Graph(int vertices);
    void addEdge(int src, int dest);
    void BFS(int startVertex);
};

Graph::Graph(int vertices) {
    numVertices = vertices;
    adjLists = new list<int>[vertices];
}

void Graph::addEdge(int src, int dest) {
    adjLists[src].push_back(dest);
}

void Graph::BFS(int startVertex) {
    bool *visited = new bool[numVertices];
    for(int i = 0; i < numVertices; i++) {
        visited[i] = false;
    }

    queue<int> q;
    visited[startVertex] = true;
    q.push(startVertex);

    while(!q.empty()) {
        int currentVertex = q.front();
        cout << currentVertex << " ";
        q.pop();

        for(auto it = adjLists[currentVertex].begin(); it != adjLists[currentVertex].end(); ++it) {
            if(!visited[*it]) {
                visited[*it] = true;
                q.push(*it);
            }
        }
    }
}

int main() {
    Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);

    cout << "BFS starting from vertex 2: ";
    g.BFS(2);

    return 0;
}

在这个示例中,我们首先定义了一个Graph类来表示图,包括成员变量numVertices和adjLists,以及构造函数、addEdge方法和BFS方法。在main函数中,我们创建了一个包含4个顶点的图,并添加了一些边。然后我们调用BFS方法从顶点2开始进行广度优先搜索,并打印出遍历结果。

运行这段代码将输出:BFS starting from vertex 2: 2 0 3 1

相关推荐
高亦真3 分钟前
今天是学习嵌入式的第31天
linux·学习·算法
程与留5 分钟前
11_常用控件速查(上):QPushButton、QLabel、QLineEdit、QComboBox
c++·qt
让学习成为一种生活方式13 分钟前
黄花蒿LHC基因家族的串联重复驱动扩张及其UV-B胁迫适应性--BMC Plant Biology
人工智能·算法·机器学习
Demon--hx17 分钟前
多态实现原理
开发语言·c++
ECT-OS-JiuHuaShan21 分钟前
共轭互逆链路论,彻底打击庸俗辩证法和不可知论
数据库·人工智能·算法·机器学习·数学建模
薛定e的猫咪23 分钟前
【大模型量化】使用 llama.cpp 完成量化、本地推理与服务化部署
人工智能·深度学习·算法·llama
薛定e的猫咪28 分钟前
【源码解读版】ContraBAR:用 CPC 对比学习替代变分推断做贝叶斯元 RL
人工智能·深度学习·学习·算法·机器学习
水饺编程1 小时前
第5章,[Win32 章节] :绘制填充区域
c语言·c++·windows·visual studio
绿算技术1 小时前
大模型本地化的经济账:DeepSeek V4 Flash 部署实测
人工智能·科技·算法·spark
翟天保Steven1 小时前
用于提升CBCT低对比度组织分辨率的三维图像后处理方法
算法·计算机视觉·图像重建·图像后处理