Topological Sorting refers to a general approach to solving problems, while the specific algorithm could be either BFS (Breadth-First Search) or DFS (Depth-First Search).

You might wonder which solution qualifies as a topological sort among the various methods you've come across.

As long as an algorithm can linearly sort a Directed Acyclic Graph (DAG), it can be considered a topological sort.

References to task scheduling, course arrangement, etc.

Topological Sorting is an algorithm specifically used for directed graphs.

Turning a Directed Acyclic Graph into a linear order is called topological sorting.

Topological sorting (Kahn's algorithm is essentially the idea of breadth-first search)

This approach also applies to problem 210.

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> inDegree(numCourses, 0);
        unordered_map<int, vector<int>> umap;
        for (int i = 0; i < prerequisites.size(); i++) {

            // prerequisites[i][0] is the course's in-degree, prerequisites[i][1] is the course's out-degree
            // Meaning: Before taking prerequisites[i][0], the course prerequisites[i][1] must be taken
            // prerequisites[i][1] -> prerequisites[i][0]
            inDegree[prerequisites[i][0]]++; // Increase the in-degree value of the current course by 1
            umap[prerequisites[i][1]].push_back(prerequisites[i][0]); // Add the course pointed to by prerequisites[i][1]
        }
        queue<int> que;
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] == 0) que.push(i); // Add all courses with an in-degree of 0, i.e., starting courses, to the queue
        }
        int count = 0;
        while (que.size()) {
            int cur = que.front();  // The current selected course
            que.pop();
            count++; // Increase the count of selected courses by 1
            vector<int> courses = umap[cur]; // Get the courses pointed to by this course, i.e., subsequent courses
            if (courses.size()) { // If there are subsequent courses
                for (int i = 0; i < courses.size(); i++) {
                    inDegree[courses[i]]--; // Decrease the in-degree of the subsequent course by 1
                    if (inDegree[courses[i]] == 0) que.push(courses[i]); // If the in-degree is 0, add it to the queue
                }
            }
        }
        if (count == numCourses) return true;
        return false;
    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Last updated:: 9/4/2025, 3:19:38 PM
Copyright © 2025 keetcoder