Skip to content

Instantly share code, notes, and snippets.

@jesuyedavid
Last active April 26, 2018 21:00
Show Gist options
  • Save jesuyedavid/b9998a54e99e3bd12c20f24d8e075744 to your computer and use it in GitHub Desktop.
Save jesuyedavid/b9998a54e99e3bd12c20f24d8e075744 to your computer and use it in GitHub Desktop.
Detect whether the graph has a cycle, and find the longest cycle.
from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
self.V=len(self.graph)
def addEdge(self, u, v):
self.graph[u].append(v)
self.V=len(self.graph)
def DFSUtil(self, v, visited):
visited[v]=True
hasC=False
print(v)
for i in self.graph[v]:
if visited[i]==False:
self.DFSUtil(i, visited)
def noVertices(self):
return self.V
def isCyclicUtil(self, v, visited, recStack):
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
def DFS(self, v):
visited =[False] * (len(self.graph))
self.DFSUtil(v, visited)
g=Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
g.DFS(0)
print("no of verticesis:", g.noVertices())
if (g.isCyclic()):
print("Cycle detected")
else:
print("No cycle detected")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment