Skip to content

Create kosaraju_algo.py #11679

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions data_structures/graph/kosaraju_algo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from collections import defaultdict

Check failure on line 1 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (INP001)

data_structures/graph/kosaraju_algo.py:1:1: INP001 File `data_structures/graph/kosaraju_algo.py` is part of an implicit namespace package. Add an `__init__.py`.

class Graph:

Check failure on line 3 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

data_structures/graph/kosaraju_algo.py:1:1: I001 Import block is un-sorted or un-formatted
def __init__(self, vertices):
self.V = vertices # Number of vertices
self.graph = defaultdict(list) # Default dictionary to store the graph

Check failure on line 7 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/graph/kosaraju_algo.py:7:1: W293 Blank line contains whitespace
def add_edge(self, u, v):
"""Function to add an edge from vertex u to vertex v."""
self.graph[u].append(v)

Check failure on line 11 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/graph/kosaraju_algo.py:11:1: W293 Blank line contains whitespace
def _dfs(self, v, visited, stack=None):
"""
A recursive function to perform DFS from vertex v.
If stack is provided, it pushes the vertices in the order of their finish time.
"""
visited[v] = True
# Recur for all vertices adjacent to this vertex
for neighbor in self.graph[v]:
if not visited[neighbor]:
self._dfs(neighbor, visited, stack)

Check failure on line 22 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/graph/kosaraju_algo.py:22:1: W293 Blank line contains whitespace
# Push the vertex to stack if it's not None (used in first DFS pass)
if stack is not None:
stack.append(v)

Check failure on line 26 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/graph/kosaraju_algo.py:26:1: W293 Blank line contains whitespace
def _transpose(self):
"""
Function to transpose (reverse) the graph.
Returns the transposed graph.
"""
transposed = Graph(self.V)
for vertex in self.graph:
for neighbor in self.graph[vertex]:
transposed.add_edge(neighbor, vertex)
return transposed

Check failure on line 37 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/graph/kosaraju_algo.py:37:1: W293 Blank line contains whitespace
def kosaraju_scc(self):
"""
Function to find and print all Strongly Connected Components (SCCs) using Kosaraju's Algorithm.

Check failure on line 40 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

data_structures/graph/kosaraju_algo.py:40:89: E501 Line too long (103 > 88)
Returns a list of SCCs, where each SCC is a list of vertices.
"""
# Step 1: Perform DFS to get the finishing times of vertices
stack = []
visited = [False] * self.V

Check failure on line 46 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/graph/kosaraju_algo.py:46:1: W293 Blank line contains whitespace
for i in range(self.V):
if not visited[i]:
self._dfs(i, visited, stack)

Check failure on line 50 in data_structures/graph/kosaraju_algo.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/graph/kosaraju_algo.py:50:1: W293 Blank line contains whitespace
# Step 2: Transpose the graph
transposed_graph = self._transpose()

# Step 3: Process vertices in the order defined by the stack
visited = [False] * self.V
sccs = [] # List to store SCCs

while stack:
v = stack.pop()
if not visited[v]:
# Collect all vertices in the current SCC
scc_stack = []
transposed_graph._dfs(v, visited, scc_stack)
sccs.append(scc_stack)

return sccs

# Example usage
if __name__ == "__main__":
g = Graph(5)
g.add_edge(1, 0)
g.add_edge(0, 2)
g.add_edge(2, 1)
g.add_edge(0, 3)
g.add_edge(3, 4)

print("Strongly Connected Components:")
sccs = g.kosaraju_scc()
for i, scc in enumerate(sccs, 1):
print(f"SCC {i}: {scc}")