Python Implementation LeetCode 210. Course Schedule II Explanation and Solution

preview_player
Показать описание
If this helps, please like this video and subscribe to my channel.

Thanks in advance. :D

Happy coding every day!
Рекомендации по теме
Комментарии
Автор

Very well explained, Java BFS implementation below.


class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
Map<Integer, Set<Integer>> graph = new HashMap<>();
int[] topologicalOrder = new int[numCourses];

// Create the adjacency list representation of the graph
for (int i = 0; i < prerequisites.length; i++) {
int dest = prerequisites[i][0];
indegree[dest]++;

int src = prerequisites[i][1];
Set<Integer> neighbors = graph.getOrDefault(src, new HashSet<Integer>());
neighbors.add(dest);

graph.put(src, neighbors);
}

// Add all vertices with 0 in-degree to the queue
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < indegree.length; i++) {
if (indegree[i] == 0)
q.add(i);
}

int i = 0;
while (!q.isEmpty()) {
int node = q.remove();
topologicalOrder[i++] = node;
// Decrement the in-degree of each neighbor of node by 1
if (graph.containsKey(node)) {
for(Integer neighbor : graph.get(node)) {
indegree[neighbor]--;

// If in-degree of a neighbor becomes 0, add it to the queue
if (indegree[neighbor] == 0) {
q.add(neighbor);
}
}
}
}

return i == numCourses ? topologicalOrder : new int[0];
}
}

alammahtab
Автор

Thanks! Very good explanation! I hope you did it in Python as a April Fool joke! :-) I prefer Java, but your Python code is also easy to understand because you always explain the logic before writing the code!

anant
Автор

Please more Python implementations :))

briang
Автор

Java please. Python has some in built fancy stuffs, less code. This won’t help others who don’t work in Python to understand what’s happening from the code. (Like something not in list, wow .. in Java so hard .. you gotta use set, maybe map with key Val).

algorithmimplementer
welcome to shbcf.ru