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<Integer, Integer> indegree = new HashMap<>();
HashMap<Integer, List<Integer>> 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<Integer>());
}
for (int[] pre : prerequisites){
neighbors.get(pre[1]).add(pre[0]);
}
Queue<Integer> 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.