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

相关推荐
hanlin0320 分钟前
动态规划专练:力扣第1035、392题
算法·leetcode·动态规划
不正经学生1 小时前
C语言大小端字节序:内存里字节的排列顺序
c语言·开发语言·arm开发·c++·算法·c#
大模型探索者1 小时前
2026金融大模型训推平台选型指南:主流厂商横向对比与私有化落地
人工智能·算法·金融
小则又沐风a2 小时前
负载均衡式在线OJ---------第二幕
linux·c++·后端
a3535413822 小时前
C++项目如何架构优化
java·c++·架构
键盘会跳舞2 小时前
C++:智能指针源码级深度拆解——从 RAII 思想到引用计数的内存安全体系
c++·智能指针·unique_ptr·shared_ptr·weak_ptr
依然鸣2 小时前
PTA团体程序设计天梯赛L2真题讲解L2-001-004
经验分享·学习·算法·深度优先·pat考试
SNAKEpc121382 小时前
OpenGL(十三)- Mip贴图
c语言·c++·图形渲染·贴图
杨航 AI4 小时前
** AI 面试算法 50 题清单**,不是单纯的 LeetCode 题号列表,而是按照“**考察概率 × 面试价值 × 你当前准备方向**”排序
算法·leetcode·面试
m0_7202450110 小时前
1543.统计好三元组(简单)
开发语言·算法