Created
August 9, 2019 19:13
-
-
Save ajinkyajawale14499/9836cce387bf76a47de750f8b0a113f7 to your computer and use it in GitHub Desktop.
Detect Cycle in a Directed Graph using DFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.io.*; | |
public class Graph{ | |
int V; | |
LinkedList<Integer> list[]; | |
Graph(int V){ | |
this.V=V; | |
list = new LinkedList[V]; | |
for(int i=0;i<V;i++){ | |
list[i]=new LinkedList<Integer>(); | |
} | |
} | |
public void addEdge(int x, int y) | |
{ | |
list[x].addFirst(y); | |
} | |
public boolean isCycle(){ | |
boolean visited[] = new boolean[V]; | |
boolean rec[]= new boolean[V]; | |
//DFS | |
for(int i=0;i<V;i++) | |
{ | |
if(isCycleUtil(i,visited,rec)) | |
return true; | |
} | |
return false; | |
} | |
public boolean isCycleUtil(int v, boolean visited[],boolean rec[]){ | |
visited[v]=true; | |
rec[v]=true; | |
// recursive call to all the adjcent vertices; | |
for(int i=0;i<list[v].size();i++) | |
{ | |
//if not visited already | |
int adjv = list[v].get(i); | |
if(!visited[adjv] && isCycleUtil(adjv , visited, rec)) | |
return true; | |
else if(rec[adjv]) | |
return true; | |
} | |
rec[v]=false; | |
return false; | |
} | |
public void printgraph(){ | |
for(int i=0;i<V;i++) | |
{ | |
LinkedList<Integer> nlist = list[i]; | |
if(nlist.isEmpty()==false){ | |
System.out.print("source = " + i + " => "); | |
for(int j=0;j<nlist.size();j++) | |
{ | |
System.out.print(" " + nlist.get(j)); | |
} | |
} | |
System.out.println(""); | |
} | |
} | |
public static void main(String [] args) | |
{ | |
Graph g = new Graph(5); | |
g.addEdge(0,1); | |
g.addEdge(0,2); | |
g.addEdge(1,3); | |
g.addEdge(3,1); | |
g.addEdge(3,4); | |
g.addEdge(4,4); | |
g.addEdge(4,0); | |
g.printgraph(); | |
boolean result = g.isCycle(); | |
System.out.println("is cycle present "+result); | |
} | |
} | |
/* SOLUTION */ | |
/* | |
source = 0 => 2 1 | |
source = 1 => 3 | |
source = 3 => 4 1 | |
source = 4 => 0 4 | |
is cycle present true | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment