codeflash/code_to_optimize/topological_sort.py
2025-06-25 16:09:29 -07:00

31 lines
774 B
Python

import uuid
from collections import defaultdict
class Graph:
def __init__(self, vertices: int):
self.graph = defaultdict(list)
self.V = vertices # No. of vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSortUtil(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i, visited, stack)
stack.insert(0, v)
def topologicalSort(self):
visited = [False] * self.V
stack = []
sorting_id = uuid.uuid4()
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i, visited, stack)
return stack, str(sorting_id)