using
System;
using
System.Collections.Generic;
public
class
GFG {
public
static
bool
DetectCycle(Dictionary<
int
, List<
int
> > graph,
int
newNode)
{
var
visited =
new
HashSet<
int
>();
var
path =
new
List<
int
>();
var
cycleExists
= Dfs(graph, newNode, visited, path);
return
cycleExists;
}
private
static
bool
Dfs(Dictionary<
int
, List<
int
> > graph,
int
node,
HashSet<
int
> visited, List<
int
> path)
{
visited.Add(node);
path.Add(node);
if
(graph.ContainsKey(node)) {
var
neighbors = graph[node];
foreach
(
var
neighbor
in
neighbors)
{
if
(visited.Contains(neighbor)) {
if
(path.Contains(neighbor)) {
return
true
;
}
}
else
{
if
(Dfs(graph, neighbor, visited,
path)) {
return
true
;
}
}
}
}
path.RemoveAt(path.Count - 1);
return
false
;
}
static
public
void
Main()
{
var
graph =
new
Dictionary<
int
, List<
int
> >{
{ 1,
new
List<
int
>{ 2, 3 } },
{ 2,
new
List<
int
>{ 1, 3 } },
{ 3,
new
List<
int
>{ 1, 2 } }
};
Console.WriteLine(DetectCycle(graph, 4));
graph.Add(4,
new
List<
int
>{ 1 });
Console.WriteLine(DetectCycle(graph, 4));
}
}