Leetcode[207] Course Schedule
17 Nov 2015###Task1 There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
2, [[1,0]] There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
2, [[1,0],[0,1]] There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Note: The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
###Python
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
finished = []
count = 0
require = [[] for i in range(numCourses)]
for pair in prerequisites:
if pair[1] not in require[pair[0]]:
require[pair[0]].append(pair[1])
for i in range(numCourses):
if len(require[i]) == 0:
count += 1
finished.append(i)
while len(finished) > 0:
cur = finished.pop(0)
#print 'now = %d' % cur
for i in range(numCourses):
if cur in require[i]:
require[i].remove(cur)
if len(require[i]) == 0:
count += 1
finished.append(i)
#print count
return count == numCourses
###Java ####bfs
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites == null) {
return false;
}
if (prerequisites.length == 0) {
return true;
}
int len = prerequisites.length;
int[] reqCourses = new int[numCourses];
for (int i = 0; i < len; i++) {
reqCourses[prerequisites[i][0]]++;
}
LinkedList<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (reqCourses[i] == 0) {
queue.offer(i);
}
}
int noPre = queue.size();
while (!queue.isEmpty()) {
int top = queue.poll();
for (int i = 0; i < len; i++) {
if (prerequisites[i][1] == top) {
reqCourses[prerequisites[i][0]]--;
if (reqCourses[prerequisites[i][0]] == 0) {
queue.offer(prerequisites[i][0]);
noPre++;
}
}
}
}
return noPre == numCourses;
}
}
####dfs
public class Solution {
public boolean dfs(HashMap<Integer, ArrayList<Integer>> map, int[] rightCourses, int crt) {
if (rightCourses[crt] == -1) {
return false;
}
if (rightCourses[crt] == 1) {
return true;
}
rightCourses[crt] = -1;
if (map.containsKey(crt)) {
for (int i = 0; i < map.get(crt).size(); i++) {
if(!dfs(map, rightCourses, map.get(crt).get(i))) {
return false;
}
}
}
rightCourses[crt] = 1;
return true;
}
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites == null) {
return false;
}
if (prerequisites.length == 0) {
return true;
}
int[] rightCourses = new int[numCourses];
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for (int i = 0; i < prerequisites.length; i++) {
if (map.containsKey(prerequisites[i][0])) {
map.get(prerequisites[i][0]).add(prerequisites[i][1]);
} else {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(prerequisites[i][1]);
map.put(prerequisites[i][0], temp);
}
}
for (int i = 0; i < numCourses; i++) {
if (!dfs(map, rightCourses, i)) {
return false;
}
}
return true;
}
}
###Points
- Topological sorting
- Like all graph search algorithm: O(E+V)
###Task2 There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]] 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]
4, [[1,0],[2,0],[3,1],[3,2]] 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].
###Java
import java.util.*;
public class Solution {
public boolean dfs(HashMap<Integer, ArrayList<Integer>> map, int[] rightCourses, int crt, ArrayList<Integer> res) {
if (rightCourses[crt] == -1) {
return false;
}
if (rightCourses[crt] == 1) {
return true;
}
rightCourses[crt] = -1;
if (map.containsKey(crt)) {
for (int i = 0; i < map.get(crt).size(); i++) {
if (!dfs(map, rightCourses, map.get(crt).get(i), res)) {
return false;
}
}
}
res.add(crt);
rightCourses[crt] = 1;
return true;
}
public int[] findOrder(int numCourses, int[][] prerequisites) {
// if (prerequisites == null || prerequisites.length == 0) {
// return null;
// }
int[] rightCourses = new int[numCourses];
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for (int i = 0; i < prerequisites.length; i++) {
if (map.containsKey(prerequisites[i][0])) {
map.get(prerequisites[i][0]).add(prerequisites[i][1]);
} else {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(prerequisites[i][1]);
map.put(prerequisites[i][0], temp);
}
}
ArrayList<Integer> res = new ArrayList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (dfs(map, rightCourses, i, res)) {
}
}
if (res.size() == numCourses) {
int[] arr = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
arr[i] = res.get(i);
}
return arr;
}
return new int[0];
}
}
###Python
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
visited = [0 for i in range(numCourses)]
require = [[] for i in range(numCourses)]
for pair in prerequisites:
if pair[1] not in require[pair[0]]:
require[pair[0]].append(pair[1])
ret = []
for i in range(numCourses):
self.dfs(require, ret, visited, i)
if len(ret) == numCourses:
return ret
else:
return []
def dfs(self, require, ret, visited, i):
if visited[i] == 1:
return True
if visited[i] == -1:
return False
visited[i] = -1
if len(require[i]) > 0:
for j in require[i]:
if not self.dfs(require, ret, visited, j):
return False
visited[i] = 1
ret.append(i)
return True
###Points
- when do dfs, need mark those nodes that have been visited.
- Dependencies(course 0 need course 1, 2,…) can be saved either in dictionary or two dimensional array(cause courses are numbers in this task)