Solution Review: Detect Cycle in Graph
This review provides a detailed analysis of the different ways to solve the "Detect a Cycle in a Graph" challenge.
We'll cover the following...
Solution: Recursion stack
Press + to interact
main.cs
LinkedList.cs
Graph.cs
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace chapter_5{class Challenge_3{// Recursive functionstatic bool detectCycleRec(Graph g, int i, bool [] visited, bool [] recNodes){// Check if current node is being visited in the same recursive callif (visited[i] == false){// Set recursive array and visited to truevisited[i] = true;recNodes[i] = true;int adjacent;LinkedList.Node adjacentNode = (g.getArray())[i].GetHead();while (adjacentNode != null){// Access adjacent node and repeat algorithmadjacent = adjacentNode.data;if ((!visited[adjacent]) && detectCycleRec(g, adjacent, visited, recNodes))return true; // Loop foundelse if (recNodes[adjacent])return true;adjacentNode = adjacentNode.nextElement;}}recNodes[i] = false;return false;}static bool detectCycle(Graph g){int num_of_vertices = g.getVertices();//Boolean Array to hold the history of visited nodes (by default-false)//Make a node visited whenever you traverse itbool [] visited = new bool[num_of_vertices];//Boolean array of vertices which will called recursivelybool [] recNodes = new bool[num_of_vertices];for (int i = 0; i < num_of_vertices; i++){visited[i] = false;recNodes[i] = false;}for (int i = 0; i < num_of_vertices; i++){ // Recursive function calledif (detectCycleRec(g, i, visited, recNodes))return true;// If cycle detected, return true}return false;}static void Main(string[] args){Graph g = new Graph(6);g.addEdge(0, 1);g.addEdge(1, 2);g.addEdge(3, 4);g.addEdge(4, 5);Console.WriteLine(detectCycle(g));g.addEdge(5, 3);Console.WriteLine(detectCycle(g));}}}
...