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

相关推荐
老赵的博客19 分钟前
c++ 是静态编译语言
开发语言·c++
Macre Aegir Thrym31 分钟前
MINIST——SVM
算法·机器学习·支持向量机
Young_Zn_Cu2 小时前
LeetCode刷题记录(持续更新中)
算法·leetcode
天选之女wow2 小时前
【代码随想录算法训练营——Day31】贪心算法——56.合并区间、738.单调递增的数字、968.监控二叉树
算法·leetcode·贪心算法
lixinnnn.2 小时前
贪心:火烧赤壁
数据结构·c++·算法
小小前端_我自坚强2 小时前
前端算法相关详解
前端·算法
Predestination王瀞潞2 小时前
类的多态(Num020)
开发语言·c++
Predestination王瀞潞2 小时前
类的继承(Num019)
开发语言·c++
Nuyoah11klay2 小时前
华清远见25072班C++学习假期10.3作业
c++
前端 贾公子2 小时前
《Vuejs设计与实现》第 5 章(非原始值响应式方案)下 Set 和 Map 的响应式代理
数据结构·算法