207. Course Schedule

Medium

mock interview的时候美国小哥提到了Kahn's Algorithm, 问我会不会。我没听过,但Course Schedule我是做过的。后来查了下,我以前写的那个用Queue的Topological sort的方法就是Kahn's Algorithm.于是自己又写了一下

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if (prerequisites == null || prerequisites.length == 0){
            return true;
        }
        HashMap indegree = new HashMap<>();
        HashMap> neighbors = new HashMap<>();
        for (int i = 0; i < numCourses; i++){
            indegree.put(i,0);
        }
        for (int[] prerequisite : prerequisites){
            indegree.put(prerequisite[0], indegree.get(prerequisite[0]) + 1);
            neighbors.put(prerequisite[1], new ArrayList());
        }
        for (int[] pre : prerequisites){
            neighbors.get(pre[1]).add(pre[0]);
        }
        Queue queue = new LinkedList<>();
        for (Integer i : indegree.keySet()){
            if (indegree.get(i) == 0){
                queue.offer(i);
            }
        }
        int count = 0;
        while (!queue.isEmpty()){
            Integer curt = queue.poll();
            count++;
            if (neighbors.containsKey(curt)){
                for (Integer nei : neighbors.get(curt)){
                    indegree.put(nei, indegree.get(nei) - 1);
                    if (indegree.get(nei) == 0){
                        queue.offer(nei);
                    }
                }
            
            }
        }
        return count == numCourses;
    }
}

Algorithm:
Steps involved in finding the topological ordering of a DAG:

Step-1: Compute in-degree (number of incoming edges) for each of the vertex present in the DAG and initialize the count of visited nodes as 0.

Step-2: Pick all the vertices with in-degree as 0 and add them into a queue (Enqueue operation)

Step-3: Remove a vertex from the queue (Dequeue operation) and then.

Increment count of visited nodes by 1.
Decrease in-degree by 1 for all its neighboring nodes.
If in-degree of a neighboring nodes is reduced to zero, then add it to the queue.
Step 5: Repeat Step 3 until the queue is empty.

Step 5: If count of visited nodes is not equal to the number of nodes in the graph then the topological sort is not possible for the given graph.

你可能感兴趣的:(207. Course Schedule)