2

The following C# algorithm I wrote detects the existence of a cycle in an undirected graph in O(n) time. It avoids recursion and takes advantage of hashing via Dictionaries and HashSets. But is there a way I can do even better?

void Main()
{
    var graph = new Dictionary<int, HashSet<int>>
    {
        { 0, new HashSet<int> { 4 } },
        { 1, new HashSet<int> { 2, 3, 4 } },
        { 2, new HashSet<int> { 1 } },
        { 3, new HashSet<int> { 1, 4 } },
        { 4, new HashSet<int> { 0, 1, 3 } }
    };

    Console.WriteLine(HasCycle(graph, 0));
}

bool HasCycle(Dictionary<int, HashSet<int>> graph, int start)
{
    var stack = new Stack<int>();
    var visited = new HashSet<int>();
    stack.Push(start);
    var curr = start;
    var prev = -1;
    while (stack.Count > 0)
    {
        prev = curr;
        curr = stack.Pop();
        visited.Add(curr);
        HashSet<int> neighbors;
        if (graph.TryGetValue(curr, out neighbors) && neighbors != null)
        {
            foreach (var neighbor in neighbors)
            {
                if (!visited.Contains(neighbor))
                {
                    stack.Push(neighbor);
                }
                else if (neighbor != prev && neighbors.Contains(prev))
                {
                    return true;
                }
            }
        }
    }
    return false;
}
Cade Bryant
  • 177
  • 10

1 Answers1

1

DFS is the best way to determine cycles in a graph

Geeksforgeeks cycle detect from undirected graph

I would refer you to study from here and apply dfs.

shaurya uppal
  • 2,335
  • 23
  • 28