-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCycleDetector.cs
More file actions
41 lines (31 loc) · 1.05 KB
/
Copy pathCycleDetector.cs
File metadata and controls
41 lines (31 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System.Collections.Generic;
using AlgorithmsAndDataStructures.DataStructures.Graph;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Misc;
public static class CycleDetector
{
// Time Complexity O(V+E)
public static bool IsCyclic(GraphVertex<int>[] graph)
{
if (graph is null) return default;
// We need to iterate over all vertices for disconnected graphs.
for (var i = 0; i < graph.Length; i++)
{
var visited = new bool[graph.Length];
visited[i] = true;
if (IsCyclic(graph, i, visited)) return true;
}
return false;
}
private static bool IsCyclic(IReadOnlyList<GraphVertex<int>> graph, int node, IList<bool> visited)
{
var adjacentVertexes = graph[node].AdjacentVertices;
foreach (var vertex in adjacentVertexes)
{
if (visited[vertex]) return true;
visited[vertex] = true;
return IsCyclic(graph, vertex, visited);
}
visited[node] = false;
return false;
}
}