-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add graphutils to detect cyclical process dependencies
- Loading branch information
Michael Hammann
committed
Apr 13, 2022
1 parent
f02dbb3
commit 16f069c
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
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 cyclic(self): | ||
"""Return True if the directed graph has a cycle. | ||
The graph must be represented as a dictionary mapping vertices to | ||
iterables of neighbouring vertices. For example: | ||
>>> cyclic({1: (2,), 2: (3,), 3: (1,)}) | ||
True | ||
>>> cyclic({1: (2,), 2: (3,), 3: (4,)}) | ||
False | ||
""" | ||
path = set() | ||
visited = set() | ||
|
||
def visit(vertex): | ||
if vertex in visited: | ||
return False | ||
visited.add(vertex) | ||
path.add(vertex) | ||
for neighbour in self.graph.get(vertex, ()): | ||
if neighbour in path or visit(neighbour): | ||
return True | ||
path.remove(vertex) | ||
return False | ||
|
||
return any(visit(v) for v in self.graph) |