The implementation is a bit different as it does not strictly follow the Kahn's algorithm maintaining a set of vertices with no incoming edges.
The implementation does not fit in my brain right now, but it is worth remembering the existence of this variation.
def topological_sort_util(
int,
v: list[list[int]],
adj: list[bool],
visited: list,
stack:
):= True
visited[v]
for i in adj[v]:
if not visited[i]:
topological_sort_util(i, adj, visited, stack)
stack.append(v)
def topological_sort(adj: list[list[int]], V: int):
# stack to store the result
= []
stack
= [False] * V
visited
for i in range(V):
if not visited[i]:
topological_sort_util(i, adj, visited, stack)
= []
result while stack:
result.append(stack.pop())return result
if __name__ == "__main__":
= 4
V = [[0, 1], [1, 2], [3, 1], [3, 2]]
edges = [[] for _ in range(V)]
adj
for s, t in edges:
adj[s].append(t)
= topological_sort(adj, V)
result print(result) # [3, 0, 1, 2]
from collections import defaultdict
def topological_sort(V, edges_map, incoming) -> list[int]:
= []
result
= []
stack for v in range(V):
if incoming[v] == 0:
stack.append(v)
while stack:
= stack.pop()
v_to_remove for target_v in edges_map[v_to_remove]:
-= 1
incoming[target_v] if incoming[target_v] == 0:
stack.append(target_v)
result.append(v_to_remove)
return result
if __name__ == "__main__":
= 4
V = [(0, 1), (1, 2), (3, 1), (3, 2)]
edges
= [0] * V
incoming for s, t in edges:
+= 1
incoming[t]
= defaultdict(list)
edges_map for s, t in edges:
edges_map[s].append(t)
= topological_sort(V, edges_map, incoming)
result print(result) # [3, 0, 1, 2]
A doubt on its time complexity arises, but I lack the ability to consider the problem right now. I'll come back later.
Rice Roni 400 Sandwitch 500 Rice 400 Mashed potatoes 500
Total 1800 kcal
push-ups
MUST:
uv
TODO: