C# does not come with a built-in graph library, but you can create your own graph data structure and implement a cycle detection algorithm. In this example, I'll use a simple adjacency list representation of a graph and implement the Depth-First Search (DFS) algorithm for cycle detection.
Here's the C# code for a simple graph class and the cycle detection algorithm:
csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class Graph
{
private Dictionary<int, List<int>> adjacencyList;
public Graph()
{
adjacencyList = new Dictionary<int, List<int>>();
}
public void AddNode(int nodeId)
{
if (!adjacencyList.ContainsKey(nodeId))
{
adjacencyList[nodeId] = new List<int>();
}
}
public void AddEdge(int node1, int node2)
{
AddNode(node1);
AddNode(node2);
adjacencyList[node1].Add(node2);
adjacencyList[node2].Add(node1);
}
public bool HasCycle()
{
return DFS(1);
}
private bool DFS(int currentNode)
{
if (adjacencyList.Count == 0)
{
return true;
}
var visited = new HashSet<int>();
var stack = new Stack<int>();
stack.Push(currentNode);
visited.Add(currentNode);
while (stack.Count > 0)
{
currentNode = stack.Pop();
if (visited.Contains(currentNode))
{
return true;
}
foreach (var neighbor in adjacencyList[currentNode])
{
if (!visited.Contains(neighbor))
{
stack.Push(neighbor);
visited.Add(neighbor);
}
}
}
return false;
}
}
You can then use this graph class to create a graph and check for cycles:
This implementation uses the Depth-First Search (DFS) algorithm to detect cycles in a graph. The DFS function is called recursively with the current node as the parameter. If a node is visited more than once, it means there's a cycle in the graph.