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

相关推荐
hweiyu0026 分钟前
数据结构:数组
数据结构·算法
你的冰西瓜29 分钟前
C++14 新特性详解:相较于 C++11 的主要改进
开发语言·c++·stl
无限进步_37 分钟前
C语言单向链表实现详解:从基础操作到完整测试
c语言·开发语言·数据结构·c++·算法·链表·visual studio
初夏睡觉38 分钟前
循环比赛日程表 题解
数据结构·c++·算法
CS_浮鱼1 小时前
【Linux编程】线程同步与互斥
linux·网络·c++
派大星爱吃鱼1 小时前
素数检验方法
算法
Greedy Alg2 小时前
LeetCode 72. 编辑距离(中等)
算法
xinxingrs2 小时前
贪心算法、动态规划以及相关应用(python)
笔记·python·学习·算法·贪心算法·动态规划
秋邱2 小时前
驾驭数据洪流:Python如何赋能您的数据思维与决策飞跃
jvm·算法·云原生·oracle·eureka·数据分析·推荐算法
侯小啾2 小时前
【23】C语言 左移(<<) 与 右移(>>) 位运算符在处理像素中的应用
c语言·算法·位运算·右移·左移