Question
There are a total of n courses you have to take, labeled from 0
to n - 1
.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
1 | 2, [[1,0]] |
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
1 | 2, [[1,0],[0,1]] |
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Solution
It’s a typical topological sorting problem.
Use a NxN matrix (N is the number of course) to represent the courses graph relationship. Use an array list to store the in-degree of every course. Use a queue to store the nodes which in-degree is 0.
Firstly, go through the input array to construct the graph matrix and record the in-degree of every node at the same time. Then go through the in-degree list, put the nodes which in-degree is 0 into the queue.
Kahn’s algorithm
1 | L ← Empty list that will contain the sorted elements |
Implementa
1 | public class Solution { |
Points
- Horizontal vs Vertical visiting 2D array.