-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycleInDirectedGraph.py
More file actions
59 lines (48 loc) · 1.39 KB
/
cycleInDirectedGraph.py
File metadata and controls
59 lines (48 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 26 11:54:20 2017
http://www.geeksforgeeks.org/detect-cycle-in-a-graph/
@author: Pratik Mishra
"""
import collections
import os
import sys
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def isCyclicUtil(self,v,visited,recStack):
# current node is marked visited
visited[v] = True
recStack[v] = True
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack) == True:
return True
elif recStack[neighbour] == True:
return True
recStack[v] = False
return False
def isCyclic(self):
visited = [False]*self.V
recStack = [False]*self.V
for node in range(self.V):
if visited[node] == False:
if self.isCyclicUtil(node,visited,recStack) == True:
return True
return False
g = Graph(4)
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,3)
g.addEdge(2,2)
g.addEdge(3,3)
if g.isCyclic() == 1:
print "Cyclic"
else:
print "Not Cyclic"