207. Curriculum (Topological Sorting)

LeetCode: 207. Course schedule

Insert picture description here


Topological sorting (Kahn algorithm is actually the idea of ​​breadth-first traversal)

Insert picture description here

Topological sorting actually uses a greedy algorithm. Greedy algorithm in a nutshell: every step is optimal, and the overall situation is optimal.
The point of greed is: currently let those nodes whose entry degree is 0 into the team;

Every time the vertices that have no predecessor are deleted from the graph, there is no need to do a real deletion operation here. We can set an in-degree array, and output a node with an in-degree of 0 in each round, remove it, and modify it The in-degree of the pointed node (-1 is enough), the node sequence obtained in turn is the node sequence of topological sorting. If there are nodes in the graph that have not been removed, it means "cannot complete all courses."



AC Code

class Solution {
    
    
    public boolean canFinish(int numCourses, int[][] p) {
    
    
        // 拓扑排序 - 广度优先遍历的思路
        int[] inDegree = new int[numCourses];
        HashSet<Integer>[] adj = new HashSet[numCourses];
        
        for(int i = 0; i < numCourses; i++) adj[i] = new HashSet<>();

        int len = p.length;
        for(int i = 0; i < len; i++) {
    
    
            inDegree[p[i][0]]++;
            adj[p[i][1]].add(p[i][0]);
        }

        Queue<Integer> queue = new LinkedList<>();
        
        // 首先加入入度为 0 的结点
        for(int i = 0; i < numCourses; i++) {
    
    
            if(inDegree[i] == 0) queue.add(i);
        }
		
		// 记录已经出队的课程数量
        int cnt = 0;
        while(!queue.isEmpty()) {
    
    
            int num = queue.poll();
            cnt++;
            // 遍历当前出队结点的所有后继结点
            for(Integer idx : adj[num]) {
    
    
                inDegree[idx]--;
                if(inDegree[idx] == 0) {
    
    
                    // 入度为 0 了
                    queue.add(idx);
                }
            }
        }

        // 移除掉的课程是否与总课程数相等
        return cnt == numCourses;
    }
}




Reference: Topological sorting, depth-first traversal

Guess you like

Origin blog.csdn.net/qq_43765535/article/details/112783057