05邮电笔记

检测无向图中的简单回路

在这篇文章中,我们将介绍如何使用深度优先搜索算法检测无向图中是否存在从给定顶点开始的简单回路。我们将使用 C++ 实现来演示。

C++ 代码

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

using namespace std;

class Graph {
public:
    int vertices;
    vector<vector<int>> adjacencyList;

    Graph(int vertices) : vertices(vertices), adjacencyList(vertices) {}

    void addEdge(int v, int w) {
        adjacencyList[v].push_back(w);
        adjacencyList[w].push_back(v);
    }

    bool hasSimpleCycle(int V) {
        unordered_set<int> visited;
        vector<int> parent(vertices, -1);

        return dfs(V, visited, parent, -1);
    }

private:
    bool dfs(int node, unordered_set<int>& visited, vector<int>& parent, int prev) {
        visited.insert(node);

        for (int neighbor : adjacencyList[node]) {
            if (visited.find(neighbor) == visited.end()) {
                parent[neighbor] = node;
                if (dfs(neighbor, visited, parent, node)) {
                    return true;
                }
            } else if (neighbor != prev && parent[node] != neighbor) {
                return true;
            }
        }

        return false;
    }
};

int main() {
    Graph graph(4);
    graph.addEdge(0, 1);
    graph.addEdge(1, 2);
    graph.addEdge(2, 3);
    graph.addEdge(3, 0);

    int startVertex = 0;
    bool result = graph.hasSimpleCycle(startVertex);

    if (result) {
        cout << "Graph has a simple cycle starting from vertex " << startVertex << endl;
    } else {
        cout << "Graph has no simple cycle." << endl;
    }

    return 0;
}


  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值