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。

相关推荐
布莱克60510 分钟前
A* 算法详解:从原理到实现
开发语言·c++·算法
多弗朗皮卡丘11 分钟前
C++ 智能指针
开发语言·c++·c++11·智能指针
段一凡-华北理工大学17 分钟前
高炉炼铁机器视觉与智能识别十八讲~系列文章15:可靠性篇:防误报、容错与识别系统的鲁棒性设计
人工智能·算法·机器学习·高炉大模型·高炉机器视觉·高炉炼铁模型开发
进化中的刀盾兽29 分钟前
从零实现 C++ AI 大模型接入 SDK(十):SessionManager 会话管理与多轮对话实现
c++
小成2023032026532 分钟前
C++~02运算符重载
开发语言·c++
某林2121 小时前
局部路径规划器 DWB:速度采样与评分权重的取值分析
人工智能·算法·架构·机器人·技术复盘
AI职业加油站1 小时前
模数共振行动解读|大模型应用工程师证书,匹配行业 RAG/Agent 落地人才需求
人工智能·学习·算法·职场和发展·职场发展
郑同学的笔记1 小时前
【c++随笔30】C++ 注册回调函数
开发语言·c++
lengxuenong2 小时前
树状数组 · 信息学学习手册2-离散化与逆序对
c++·学习·算法
琳达爱分享2 小时前
五个线程同时去换 token,四个被踢下线:刷新接口其实不是幂等的
后端·算法·架构