2020-06-16 17:09:59 +00:00
---
id: cyc
2020-06-22 19:59:16 +00:00
title: Cycle Detection
2020-06-16 17:09:59 +00:00
author: Siyong Huang
prerequisites:
2020-06-22 14:26:06 +00:00
-
- Silver - Functional Graphs
2020-06-16 17:09:59 +00:00
-
2020-06-20 22:27:52 +00:00
- Gold - Breadth First Search
2020-06-22 19:59:16 +00:00
description: A simple cycle is a non-empty path of distinct edges that start and end at the same vertex such that no vertex appears more than once. Describes how to detect cycles in both directed and undirected graphs.
2020-06-16 17:09:59 +00:00
---
2020-06-20 22:27:52 +00:00
*Cycle detection* determines properties of cycles in a directed or undirected graph, such as whether each node of the graph is part of a cycle or just checking whether a cycle exists.
2020-06-17 22:18:07 +00:00
2020-06-20 22:27:52 +00:00
## Undirected Graphs
2020-06-16 17:09:59 +00:00
2020-06-20 22:27:52 +00:00
- [CSES Round Trip ](https://cses.fi/problemset/task/1669 )
2020-06-16 17:09:59 +00:00
2020-06-20 22:27:52 +00:00
BFS-Cycle
2020-06-16 17:09:59 +00:00
2020-06-20 22:27:52 +00:00
## Directed Graphs
- [CSES Round Trip II ](https://cses.fi/problemset/task/1678 )
2020-06-16 17:09:59 +00:00
The same general idea is implemented below to find any cycle in a directed graph (if one exists).
```cpp
//UNTESTED
bool visited[MAXN], on_stack[MAXN];
vector< int > adj[MAXN];
vector< int > cycle;
bool dfs(int n)
{
visited[n] = on_stack[n] = true;
for(int u:adj[n])
{
if(on_stack[u])
return cycle.push_back(v), cycle.push_back(u), on_stack[n] = on_stack[u] = false, true;
else if(!visited[u])
{
if(dfs(u))
if(on_stack[n])
return cycle.push_back(n), on_stack[n] = false, true;
else
return false;
if(!cycle.empty())
return false;
}
}
on_stack[n] = false;
return false;
}
int main()
{
//take input, etc
for(int i = 1;cycle.empty() & & i < = N;i++)
dfs(i);
if(cycle.empty())
printf("No cycle found!\n");
else
{
reverse(cycle.begin(), cycle.end());
printf("Cycle of length %u found!\n", cycle.size());
for(int n : cycle) printf("%d ", n);
printf("\n");
}
}
```
### Problems
2020-06-22 14:26:06 +00:00
- [CSES Graph Girth ](https://cses.fi/problemset/task/1707 )
- shortest cycle
2020-06-16 17:09:59 +00:00