0
0
DSA Cprogramming~30 mins

Topological Sort Using Kahn's Algorithm BFS in DSA C - Build from Scratch

Choose your learning style9 modes available
Topological Sort Using Kahn's Algorithm BFS
📖 Scenario: Imagine you are managing tasks in a project where some tasks must be done before others. You want to find an order to do all tasks without breaking any rules.
🎯 Goal: Build a program in C that uses Kahn's Algorithm with BFS to find a valid order of tasks (topological sort) from given dependencies.
📋 What You'll Learn
Create an adjacency list to represent the directed graph of tasks
Create an array to store the in-degree (number of incoming edges) for each task
Use a queue to process tasks with zero in-degree
Implement Kahn's Algorithm to find the topological order
Print the topological order of tasks
💡 Why This Matters
🌍 Real World
Topological sorting is used in project scheduling, build systems, and resolving dependencies in software packages.
💼 Career
Understanding topological sort helps in roles like software development, project management, and systems engineering where task ordering and dependency resolution are critical.
Progress0 / 4 steps
1
Create the graph representation
Create an adjacency list called graph as an array of integer arrays with size 6, and an integer array called in_degree of size 6 initialized to 0.
DSA C
Hint

Use a 2D array for graph and a 1D array for in_degree, both of size 6.

2
Add edges and compute in-degree
Add edges to graph to represent these dependencies: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1. Update the in_degree array accordingly for each edge.
DSA C
Hint

For each edge u->v, set graph[u][v] = 1 and increment in_degree[v].

3
Implement Kahn's Algorithm BFS
Create an integer array queue of size 6 and two integers front and rear initialized to 0. Enqueue all nodes with in_degree 0. Then, use a while loop to dequeue nodes, add them to topo_order array, and reduce in-degree of their neighbors, enqueueing neighbors when their in-degree becomes 0.
DSA C
Hint

Use a queue to process nodes with zero in-degree and update neighbors' in-degree inside the while loop.

4
Print the topological order
Print the elements of the topo_order array separated by spaces in a single line.
DSA C
Hint

Use a for loop to print each element of topo_order separated by spaces.