Skip to content

Commit 9c94423

Browse files
committed
Fix topological sort order
Fixes #12192
1 parent 52602ea commit 9c94423

File tree

1 file changed

+35
-10
lines changed

1 file changed

+35
-10
lines changed

graphs/basic_graphs.py

+35-10
Original file line numberDiff line numberDiff line change
@@ -155,26 +155,46 @@ def dijk(g, s):
155155

156156

157157
def topo(g, ind=None, q=None):
158+
"""
159+
Perform topological sorting on a directed acyclic graph (DAG).
160+
161+
Args:
162+
g (dict): Dictionary of edges representing the graph.
163+
ind (list, optional): List of in-degrees of nodes. Defaults to None.
164+
q (deque, optional): Queue for processing nodes. Defaults to None.
165+
166+
Returns:
167+
list: List of nodes in topologically sorted order.
168+
169+
Note:
170+
The function returns the list in the correct order from top to bottom.
171+
The order is reversed before returning to ensure the correct topological sort.
172+
173+
Example:
174+
>>> graph = {1: [2, 3], 2: [4], 3: [4], 4: []}
175+
>>> topo(graph)
176+
[1, 2, 3, 4]
177+
"""
158178
if q is None:
159179
q = [1]
160180
if ind is None:
161-
ind = [0] * (len(g) + 1) # SInce oth Index is ignored
181+
ind = [0] * (len(g) + 1) # Since 0th Index is ignored
162182
for u in g:
163183
for v in g[u]:
164184
ind[v] += 1
165185
q = deque()
166186
for i in g:
167187
if ind[i] == 0:
168188
q.append(i)
169-
if len(q) == 0:
170-
return
171-
v = q.popleft()
172-
print(v)
173-
for w in g[v]:
174-
ind[w] -= 1
175-
if ind[w] == 0:
176-
q.append(w)
177-
topo(g, ind, q)
189+
result = []
190+
while q:
191+
v = q.popleft()
192+
result.append(v)
193+
for w in g[v]:
194+
ind[w] -= 1
195+
if ind[w] == 0:
196+
q.append(w)
197+
return result[::-1] # Reverse the result list before returning
178198

179199

180200
"""
@@ -375,3 +395,8 @@ def find_isolated_nodes(graph):
375395
if not graph[node]:
376396
isolated.append(node)
377397
return isolated
398+
399+
400+
if __name__ == "__main__":
401+
import doctest
402+
doctest.testmod()

0 commit comments

Comments
 (0)