Skip to content

Instantly share code, notes, and snippets.

@jimexist
Created May 14, 2015 18:33
Show Gist options
  • Select an option

  • Save jimexist/71baa5d6c829ccb9e720 to your computer and use it in GitHub Desktop.

Select an option

Save jimexist/71baa5d6c829ccb9e720 to your computer and use it in GitHub Desktop.
Solution to leetcode course schedule II
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[][] deps = {{1, 0}};
System.out.printf("%s\n", Arrays.toString(new Solution().findOrder(2, deps)));
}
private static Integer append(int i, Map<Integer, List<Integer>> map, Map<Integer, Integer> depthMap) {
if (depthMap.containsKey(i)) {
if (null == depthMap.get(i)) {
return null;
} else {
return depthMap.get(i);
}
} else if (!map.containsKey(i)) {
depthMap.put(i, 0);
return 0;
} else {
int val = 0;
depthMap.put(i, null);
for (int child : map.get(i)) {
Integer sub = append(child, map, depthMap);
if (null == sub) {
return sub;
}
val = Math.max(val, 1 + sub);
}
depthMap.put(i, val);
return val;
}
}
private static Map<Integer, List<Integer>> buildDeps(int[][] prerequisites) {
Map<Integer, List<Integer>> deps = new HashMap<Integer, List<Integer>>();
for (int[] pair : prerequisites) {
int child = pair[0];
int parent = pair[1];
if (!deps.containsKey(parent)) {
deps.put(parent, new ArrayList<Integer>());
}
deps.get(parent).add(child);
}
return deps;
}
private static int[] convert(List<Integer> list) {
int[] result = new int[list.size()];
int i=0;
for (int x : list) result[i++] = x;
return result;
}
public int[] findOrder(int numCourses, int[][] prerequisites) {
if (numCourses == 0) {
return new int[0];
}
Map<Integer, List<Integer>> deps = buildDeps(prerequisites);
final Map<Integer, Integer> depthMap = new HashMap<Integer, Integer>();
for (int i=0; i<numCourses; ++i) {
if (null == append(i, deps, depthMap)) {
return new int[0];
}
}
List<Integer> result = new ArrayList<Integer>(depthMap.keySet());
System.out.printf("%s\n", depthMap);
Collections.sort(result, new Comparator<Integer>(){
@Override
public int compare(Integer lhs, Integer rhs) {
return - Integer.compare(depthMap.get(lhs), depthMap.get(rhs));
}
});
return convert(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment