Topological Sort and Deadlock (cycle detection)

 Cycle Detection:

To detect a cycle in graph we need to use dfs algorithm, we need to maintain a stack while traversing, we will do this for every node.

 Pseudocode:

       function checkCycle(v):

                    if inStack[v] = =true:

                            return true;

                    if visited[v] = =true:

                            return false:

                    inStack[v] = true 

                     visited[v] =true

                       for each neighbor of v:

                                    if(checkCycle(child of v)):

                                             return v 

                        inStack[v]=false;

                        return false; 

 function check():

            for each node v:

                    if(checkCycle(v))

                                return true

             return false

    So for each node we will start depth check and keep adding items in stack, if at any point any item already present in stack comes again then we will return cycle is true, we make sure to remove elements from stack while backtracking.

Topological sort:

  We can extend above algorithm to find topological order of the graph.

    Topological order is a order where if there is a path between u->v then u will come before v. there can be multiple such order but this one rule should follow. This ordering is done for directed graph and cycle should not be present i.e Directed Acyclic Graph (DAG).

 In above algorithm if we add a stack, and we add elements when a node comes with no children or when all the children of a node is itereated.

 

Pseudocode:

       function checkCycle(v):

                    if inStack[v] = =true:

                            return true;

                    if visited[v] = =true:

                            return false:

                    inStack[v] = true 

                     visited[v] =true

                       for each neighbor of v:

                                    if(checkCycle(child of v)):

                                             return v 

                        orderedList.add(v);

(orderedList is a stack or a list in which elements are added at first) 

                        inStack[v]=false;

                        return false; 

 function check():

            for each node v:

                    if(checkCycle(v))

                                return true

             return false

 Questions Solved:

https://leetcode.com/problems/course-schedule/

https://leetcode.com/problems/course-schedule-ii/


  

Comments

Popular posts from this blog

LeetCode 3Sum

30. Substring with Concatenation of All Words

Lowest common ancestor in a binary Tree