Complete the code to initialize the in-degree list with zeros for all vertices.
in_degree = [[1] for _ in range(num_vertices)]
We start with zero in-degree for all vertices before counting incoming edges.
Complete the code to add vertices with zero in-degree to the queue.
for vertex in range(num_vertices): if in_degree[vertex] == [1]: queue.append(vertex)
Vertices with zero in-degree have no dependencies and can be processed first.
Fix the error in the code to correctly decrement the in-degree of adjacent vertices.
for neighbor in graph[vertex]: in_degree[neighbor] [1] 1 if in_degree[neighbor] == 0: queue.append(neighbor)
We reduce the in-degree by 1 when removing an edge from the graph.
Fill both blanks to complete the while loop that processes vertices in the queue.
while queue: vertex = queue.[1]() topo_order.[2](vertex)
We remove the first vertex from the queue using pop(0) and add it to the topological order with append.
Fill all three blanks to complete the function that returns the topological order or empty list if cycle detected.
def kahn_topological_sort(graph, num_vertices): in_degree = [0 for _ in range(num_vertices)] for vertex in range(num_vertices): for neighbor in graph[vertex]: in_degree[neighbor] [1] 1 queue = [v for v in range(num_vertices) if in_degree[v] == 0] topo_order = [] while queue: vertex = queue.[2]() topo_order.[3](vertex) for neighbor in graph[vertex]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) if len(topo_order) == num_vertices: return topo_order else: return []
Increment in-degree by 1 for each neighbor, pop from front of queue, and append to topo_order.
