Course Schedule II
Problem Statement :
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai, bi < numCourses ai != bi All the pairs [ai, bi] are distinct.
Solution :
Solution in C :
int cmpfunc(const void* a, const void* b){
int* arr1 = *(int**)a;
int* arr2 = *(int**)b;
return arr1[1] - arr2[1];
}
int BTS(int** arr, int arrSize, int val){
int left = 0, right = arrSize-1;
int mid;
while(left < right){
mid = left + (right - left)/2 ;
if(arr[mid][1] >= val)
right = mid;
else
left = mid + 1;
}
if(arr[left][1] == val)
return left;
else
return -1;
}
int* findOrder(int numCourses, int** prerequisites, int prerequisitesSize, int* prerequisitesColSize, int* returnSize){
int* prereqCn = calloc(numCourses , sizeof(int));
for(int i = 0; i < prerequisitesSize; i++){
prereqCn[ prerequisites[i][0] ]++;
}
//depend test case : queue can be smaller
int* queue = malloc(1000 * sizeof(int));
int Qidx = 0;
for(int i = 0; i < numCourses; i++){
if(prereqCn[i] == 0){
queue[Qidx] = i;
Qidx++;
}
}
if(prerequisitesSize > 0)
qsort(prerequisites, prerequisitesSize, sizeof(int*), cmpfunc);
int* ans = malloc( numCourses * sizeof(int)) ;
int andIdx = 0;
while(Qidx){
Qidx--;
int val = queue[Qidx];
ans[andIdx] = val;
andIdx++;
if(prerequisitesSize > 0){
int k = BTS(prerequisites, prerequisitesSize, val);
if(k != -1){
while(k < prerequisitesSize && prerequisites[k][1] == val){
prereqCn[ prerequisites[k][0] ]--;
if( prereqCn[ prerequisites[k][0] ] == 0 ){
queue[Qidx] = prerequisites[k][0] ;
Qidx++;
}
k++;
}
}
}
}
//if collision happen, then no ans
if(andIdx != numCourses){
*returnSize = 0;
free(ans);
return NULL;
}
else
*returnSize = numCourses;
return ans;
}
Solution in C++ :
typedef vector<vector<int>> vvi;
typedef vector<int> vi;
class Solution {
private:
void dfs(int s, vvi& graph, vi& pro, vi& res, bool& cycle) {
if (pro[s] > 0) {
if (pro[s] == 1) cycle = true;
return;
}
pro[s] = 1;
for (int u: graph[s]) dfs(u, graph, pro, res, cycle);
pro[s] = 2;
res.push_back(s);
}
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vvi graph(numCourses);
vi pro(numCourses);
vi res, buf;
bool cycle = false;
for (int i = 0; i < prerequisites.size(); i++) {
int a = prerequisites[i][0], b = prerequisites[i][1];
graph[b].push_back(a);
}
for (int i = 0; i < numCourses; i++) {
dfs(i, graph, pro, res, cycle);
if (cycle == true) return buf;
}
reverse(res.begin(), res.end());
return res;
}
};
Solution in Java :
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
boolean[] visited = new boolean[prerequisites.length];
boolean[] done = new boolean[numCourses];
int[] res = new int[numCourses];
for (int[] p : prerequisites) {
indegree[p[1]]++;
}
int index = 0;
boolean hasNewVertex = true;
while(hasNewVertex) {
hasNewVertex = false;
for (int i = 0; i < prerequisites.length; i++) {
if (!visited[i]) {
int cur = prerequisites[i][0];
int pre = prerequisites[i][1];
if (indegree[cur] == 0) {
// start from indegree == 0, cut edges, until no indegree = 0
visited[i] = true;
indegree[pre]--;
hasNewVertex = true;
if(!done[cur]){
done[cur] = true;
res[index++] = cur;
}
}
}
}
}
for (int i = 0 ; i < numCourses; i++) {
if (!done[i]) {
res[index++] = i;
}
}
for (int i = 0; i < numCourses/2; i++) {
int temp = res[i];
res[i] = res[numCourses-1-i];
res[numCourses-1-i] = temp;
}
for (int i = 0; i < numCourses; i++) {
if (indegree[i] != 0) {
return new int[]{};
}
}
return res;
}
}
Solution in Python :
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = {}
for i in range(numCourses):
graph[i]=[]
for c,pc in prerequisites:
graph[c].append(pc)
ans = []
finallyVisited=set()
visited = set()
def dfs(course):
if course in visited:
return False
if course in finallyVisited:
return True
visited.add(course)
for nei in graph[course]:
if not dfs(nei):
return False
ans.append(course)
finallyVisited.add(course)
visited.remove(course)
return True
for key,val in graph.items():
if not dfs(key):
return []
return ans
View More Similar Problems
Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →Ticket to Ride
Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o
View Solution →