当前位置: 首页 > article >正文

【图论】判断图中有环的两种方法及实现

判断图中有环的两种方法及实现

在图论中,检测有向图是否存在环是常见问题。本文将介绍两种主流方法:DFS三色标记法拓扑排序(Kahn算法),并提供对应的C++代码实现。


方法一:DFS三色标记法

核心思想

通过深度优先搜索(DFS)遍历图,使用三种颜色标记节点状态:

  • 0(未访问):节点尚未被访问。
  • 1(访问中):节点正在被访问,其后续节点仍在递归中。
  • 2(已访问):节点及其所有后代均已处理完毕。

如果在遍历过程中遇到状态为1的节点,说明存在环

时间复杂度

  • O(V + E),其中V为节点数,E为边数。

C++代码实现

#include <vector>
using namespace std;

bool hasCycleDFS(vector<vector<int>>& graph, int node, vector<int>& color) {
    color[node] = 1; // 标记为“访问中”
    for (int neighbor : graph[node]) {
        if (color[neighbor] == 0) { // 未访问的节点
            if (hasCycleDFS(graph, neighbor, color)) return true;
        } else if (color[neighbor] == 1) { // 遇到访问中的节点,存在环
            return true;
        }
    }
    color[node] = 2; // 标记为“已访问”
    return false;
}

bool hasCycle(vector<vector<int>>& graph) {
    int n = graph.size();
    vector<int> color(n, 0); // 初始化所有节点为未访问
    for (int i = 0; i < n; ++i) {
        if (color[i] == 0 && hasCycleDFS(graph, i, color)) {
            return true;
        }
    }
    return false;
}

方法二:拓扑排序(Kahn算法)

核心思想

  1. 统计每个节点的入度(指向该节点的边数)。
  2. 将所有入度为0的节点加入队列。
  3. 依次处理队列中的节点,减少其邻居的入度。若邻居入度变为0,则加入队列。
  4. 若最终处理的节点数不等于总节点数,则存在环。

时间复杂度

  • O(V + E),其中V为节点数,E为边数。

C++代码实现

#include <vector>
#include <queue>
using namespace std;

bool hasCycleTopo(vector<vector<int>>& graph) {
    int n = graph.size();
    vector<int> indegree(n, 0);
    queue<int> q;

    // 计算初始入度
    for (int u = 0; u < n; ++u) {
        for (int v : graph[u]) {
            indegree[v]++;
        }
    }

    // 入度为0的节点入队
    for (int i = 0; i < n; ++i) {
        if (indegree[i] == 0) q.push(i);
    }

    int cnt = 0; // 记录处理的节点数
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        cnt++;
        for (int v : graph[u]) {
            if (--indegree[v] == 0) {
                q.push(v);
            }
        }
    }

    return cnt != n; // 存在环时cnt < n
}

方法对比与适用场景

方法优势劣势适用场景
DFS三色标记法可同时处理其他任务(如路径记录)递归深度可能较大需要深度遍历信息的场景
拓扑排序无需递归,适合大规模图仅提供是否存在环的结果只需判断环或需要拓扑序列的场景

完整测试代码

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

// DFS三色标记法
bool hasCycleDFS(vector<vector<int>>& graph, int node, vector<int>& color) {
    color[node] = 1;
    for (int v : graph[node]) {
        if (color[v] == 0) {
            if (hasCycleDFS(graph, v, color)) return true;
        } else if (color[v] == 1) {
            return true;
        }
    }
    color[node] = 2;
    return false;
}

bool hasCycleDFS(vector<vector<int>>& graph) {
    int n = graph.size();
    vector<int> color(n, 0);
    for (int i = 0; i < n; ++i) {
        if (color[i] == 0 && hasCycleDFS(graph, i, color)) {
            return true;
        }
    }
    return false;
}

// 拓扑排序
bool hasCycleTopo(vector<vector<int>>& graph) {
    int n = graph.size();
    vector<int> indegree(n, 0);
    queue<int> q;

    for (auto& edges : graph) {
        for (int v : edges) indegree[v]++;
    }
    for (int i = 0; i < n; ++i) {
        if (indegree[i] == 0) q.push(i);
    }

    int cnt = 0;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        cnt++;
        for (int v : graph[u]) {
            if (--indegree[v] == 0) q.push(v);
        }
    }

    return cnt != n;
}

int main() {
    // 示例:有环图 0->1->2->0
    vector<vector<int>> graph = {{1}, {2}, {0}};

    cout << "DFS三色标记法结果: " << (hasCycleDFS(graph) ? "有环" : "无环") << endl;
    cout << "拓扑排序结果: " << (hasCycleTopo(graph) ? "有环" : "无环") << endl;

    return 0;
}

通过这两种方法,可以高效判断有向图中是否存在环。实际应用中,若需要拓扑序列则优先选择Kahn算法,若需深度遍历信息则选择DFS三色标记法。

(本文由deepseek总结生成)


http://www.kler.cn/a/571011.html

相关文章:

  • C# 矩形面积和周长的程序(Program for Area And Perimeter Of Rectangle)
  • 【项目管理】基于 C 语言的 QQ 聊天室实现(TCP + 多线程 + SQLite3)
  • 微软具身智能感知交互多面手!Magma:基于基础模型的多模态AI智能体
  • 信号量和互斥量 在linux下的API是什么?
  • 几道考研数学题求解
  • 清影2.0(AI视频生成)技术浅析(六):多模态融合与智能推荐
  • PL0 虚拟机
  • 【MySQL】【已解决】Windows安装MySQL8.0时的报错解决方案
  • 基于coze+微信小程序的ai对话
  • Libgdx游戏开发系列教程(2)——接水滴游戏实现
  • 23种设计模式之《责任链模式(Chain of Responsibility)》在c#中的应用及理解
  • 自动计算相机pose,pyrender渲染例子
  • MIPI接口:(4)MIPI CSI-2协议详解(上)
  • JavaWeb5、Maven
  • mssql2008与mssql2014绿色版数据库软件,免安装,下载解压就可以使用
  • 计算机网络基础:服务器远程连接管理(Telnet命令)
  • How to use VRX on ubuntu20.04 with ROS1 Noetic?[2]
  • jenkins集成docker发布java项目
  • 各种类型网络安全竞赛有哪些 网络安全大赛的简称
  • 智能家居的二次进化:当三维设计遇见场景芯片