Build order with dependencies
Standard · Write code · about 12 min
Projects are numbered 0 to n − 1. An edge u → v in graph means project u must be built before project v. Return the build order. When several projects are ready, build the smallest-numbered one first, so the answer is unique. Return [] if the dependencies form a cycle.
Example 1
Input:
[{"n":6,"edges":[[0,3],[1,3],[3,4],[2,4],[4,5]],"directed":true}]
Output:
[0,1,2,3,4,5]
0, 1 and 2 are ready at the start. Labels show in-degrees.
Example 2
Input:
[{"n":4,"edges":[[3,0],[2,1]],"directed":true}]
Output:
[2,1,3,0]
2 and 3 are ready. Build 2, which makes 1 ready. 1 is smaller than 3, so it goes next.
Constraints
- 1 ≤ n ≤ 200
- 0 ≤ edges ≤ 600
Learn the idea first: Topological sort: Kahn's algorithm and DFS finishing order, a visual lesson.
More Topological sort: Kahn's algorithm and DFS finishing order problems
- Topological order Warm-up
- Tick the in-degree down Warm-up
- From finishing order to topological order Standard
- Course schedule II Standard
- Alien dictionary Challenge