判断有向图有没有环

这里记录一种简单(码量小)的方法。

核心思想是借助dfs/递归来实现

借助vis数组保存三种状态

  1. vis[u]=0 该节点尚未被访问
  2. vis[u]=1 该节点正在被访问(正在当前的递归中)
  3. vis[u]=2 该节点已经完成了访问
#include <bits/stdc++.h>
using namespace std;

const int maxn = 5e3 + 10;
vector<int> g[maxn];
int vis[maxn];
bool cyc=0;//是否有环

void dfs(int v){
    vis[v]=1;//节点加入递归
    for(auto p:g[v]){
        if(vis[p]==1){//该节点在当前递归中,说明形成了环
            cyc=1;
        }else if(vis[p]==0){//没有被访问,则继续递归
            dfs(p);
        }
    }
    vis[v]=2;//节点结束递归
}

int main(){
    //...
    for(int i=1;i<=n;i++){
        if(vis[i]==0) dfs(i);
    }
    //...
}


贴一道题:https://codeforces.com/contest/1217/problem/D

在C++中,我们可以使用深度优先搜索(DFS)或拓扑排序来判断有向图是否存在。这里给出一种基于DFS的简单实现: ```cpp #include <iostream> #include <vector> #include <stack> using namespace std; // 定义邻接表表示有向图 class Graph { public: int V; // 图的顶点数 vector<vector<int>> adj; // 存储每个顶点的邻接列表 Graph(int v) : V(v), adj(v, vector<int>()) {} void addEdge(int u, int v) { adj[u].push_back(v); } bool isCyclicUtil(int v, bool visited[], stack<int>& stk) { // Mark the current node as visited and push it to the stack. visited[v] = true; stk.push(v); // Recur for all the vertices adjacent to this vertex for (int i = 0; i < adj[v].size(); ++i) if (!visited[adj[v][i]]) if (isCyclicUtil(adj[v][i], visited, stk)) return true; // If none of the adjacent vertices are in cycle, // pop from stack and move to next adjacent vertex. else stk.pop(); return false; } // Returns true if graph has a cycle, else false bool isCycle() { bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; stack<int> stk; for (int i = 0; i < V; i++) { if (visited[i]) continue; if (isCyclicUtil(i, visited, stk)) { delete[] visited; return true; // A cycle is found } } delete[] visited; return false; // No cycle found } }; int main() { Graph g(4); // 创建一个有4个顶点的图 g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); // 这里存在一个 if (g.isCycle()) cout << "The graph contains a cycle.\n"; else cout << "The graph does not contain a cycle.\n"; return 0; } ``` 这个代码首先创建了一个有向图,然后使用`isCycle`函数通过递归调用`isCyclicUtil`检查图中是否。如果在遍历过程中发现,则返回true;否则,在遍历完整个图后返回false。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值