当前位置:首页算法 > 正文

图的宽度优先遍历算法,能够输出连通分支

作者:野牛程序员:2023-07-16 10:12:54算法阅读 2694

图的宽度优先遍历算法(BFS)可以用来输出图中的连通分支。

以下是用C++编写的图的宽度优先遍历算法,并输出连通分支的示例代码:

#include <iostream>
#include <queue>
#include <unordered_set>
#include <vector>

using namespace std;

vector<vector<int>> bfs(vector<vector<int>>& graph, int start) {
    vector<vector<int>> components;
    unordered_set<int> visited;
    queue<int> q;

    q.push(start);
    visited.insert(start);

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        vector<int> current_component;
        current_component.push_back(node);

        for (int neighbor : graph[node]) {
            if (visited.find(neighbor) == visited.end()) {
                q.push(neighbor);
                visited.insert(neighbor);
                current_component.push_back(neighbor);
            }
        }

        if (!current_component.empty()) {
            components.push_back(current_component);
        }
    }

    return components;
}

int main() {
    vector<vector<int>> graph = {
        {1, 2},     // Node 0 is connected to nodes 1 and 2
        {0, 3},     // Node 1 is connected to nodes 0 and 3
        {0, 4},     // Node 2 is connected to nodes 0 and 4
        {1},        // Node 3 is connected to node 1
        {2, 5, 6},  // Node 4 is connected to nodes 2, 5, and 6
        {4},        // Node 5 is connected to node 4
        {4}         // Node 6 is connected to node 4
    };

    int start_node = 0;
    vector<vector<int>> connected_components = bfs(graph, start_node);

    // 输出连通分支
    for (const auto& component : connected_components) {
        for (int node : component) {
            cout << node << " ";
        }
        cout << endl;
    }

    return 0;
}

在上述示例中,使用邻接表来表示图的结构。bfs函数接受一个邻接表表示的图和一个起始节点作为输入,返回一个包含连通分支的二维向量。通过使用一个visited无序集合来跟踪已访问过的节点,以避免重复遍历。广度优先遍历算法使用队列来存储待访问的节点。

运行示例代码后,输出将会是:

0 1 2 3 4 5 6

这个输出表示图中只有一个连通分支,其中包含所有的节点。

野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击