Untitled
unknown
plain_text
a year ago
1.4 kB
1
Indexable
Never
class Graph { private final int V; private final int[][] adj; public Graph(int V) { this.V = V; adj = new int[V][V]; } private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; for (int c = 0; c < V; c++) { if (adj[i][c] == 1) { if (isCyclicUtil(c, visited, recStack)) return true; } } recStack[i] = false; return false; } private void addEdge(int source, int dest) { adj[source][dest] = 1; } private boolean isCyclic() { boolean[] visited = new boolean[V]; boolean[] recStack = new boolean[V]; for (int i = 0; i < V; i++) { if (isCyclicUtil(i, visited, recStack)) return true; } return false; } public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if (graph.isCyclic()) System.out.println("Graph contains cycle"); else System.out.println("Graph doesn't contain cycle"); } }