Fix layered topological sort bug in Graph class
This commit is contained in:
parent
2b2fd3fa8d
commit
b6a2f7dd24
1 changed files with 5 additions and 1 deletions
|
|
@ -631,7 +631,7 @@ class Graph:
|
||||||
vertices: List[Vertex],
|
vertices: List[Vertex],
|
||||||
) -> List[List[str]]:
|
) -> List[List[str]]:
|
||||||
"""Performs a layered topological sort of the vertices in the graph."""
|
"""Performs a layered topological sort of the vertices in the graph."""
|
||||||
|
vertices_ids = [vertex.id for vertex in vertices]
|
||||||
# Queue for vertices with no incoming edges
|
# Queue for vertices with no incoming edges
|
||||||
queue = deque(
|
queue = deque(
|
||||||
vertex.id for vertex in vertices if self.in_degree_map[vertex.id] == 0
|
vertex.id for vertex in vertices if self.in_degree_map[vertex.id] == 0
|
||||||
|
|
@ -646,6 +646,10 @@ class Graph:
|
||||||
vertex_id = queue.popleft()
|
vertex_id = queue.popleft()
|
||||||
layers[current_layer].append(vertex_id)
|
layers[current_layer].append(vertex_id)
|
||||||
for neighbor in self.successor_map[vertex_id]:
|
for neighbor in self.successor_map[vertex_id]:
|
||||||
|
# only vertices in `vertices` are considered
|
||||||
|
if neighbor not in vertices_ids:
|
||||||
|
continue
|
||||||
|
|
||||||
self.in_degree_map[neighbor] -= 1 # 'remove' edge
|
self.in_degree_map[neighbor] -= 1 # 'remove' edge
|
||||||
if self.in_degree_map[neighbor] == 0:
|
if self.in_degree_map[neighbor] == 0:
|
||||||
queue.append(neighbor)
|
queue.append(neighbor)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue