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

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

在图论中,检测有向图是否存在环是常见问题。本文将介绍两种主流方法: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总结生成)

在C语言中,判断无向是否存在(也称为路)通常使用深度优先搜索(Depth-First Search, DFS)或广度优先搜索(Breadth-First Search, BFS)。这里我将简述DFS方法: **使用深度优先搜索(DFS判断:** 1. **邻接表表示法:** - 对每个未访问过的节点进行递归探索。 - 使用一个数组或链表标记已访问的节点,避免重复访问。 - 如果在遍历过程中发现一个节点已经被标记为已访问(并且它不是当前节点),则说明存在。 - 如果对所有节点都完成了递归探索,且没有发现,那么可以确定。 ```c void dfs(int node, int visited[], bool graph[]) { visited[node] = 1; // 标记为已访问 for (int i = 0; i < num_nodes; i++) { if (graph[node][i] && !visited[i]) { // 遍历邻居 if (dfs(i, visited, graph)) return true; // 如果找到,返回true } else if (graph[node][i] && visited[i] == 1) { // 如果邻居已经访问过且有边相连 return true; } } visited[node] = 0; // 搜索结束,恢复节点状态 return false; } bool hasCycle(int graph[]) { int visited[num_nodes]; for (int i = 0; i < num_nodes; i++) { if (!visited[i] && dfs(i, visited, graph)) { return true; } } return false; // 中无 } ``` **使用BFS判断:** BFS同样可以检测,通过检查是否所有的节点都能在固定时间内被访问到。如果发现某个节点两次出现在队列中,就表明存在。 ```c bool hasCycle_bfs(int graph[][num_nodes]) { queue<int> q; for (int i = 0; i < num_nodes; i++) { if (!visited[i]) q.push(i); while (!q.empty()) { int top = q.front(); q.pop(); visited[top] = 1; for (int j = 0; j < num_nodes; j++) { if (graph[top][j] && !visited[j]) { q.push(j); } } if (q.size() > num_nodes) // 如果节点数超过节点总数,说明存在 return true; } } return false; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值