Skip to content

Commit

Permalink
course shed ii
Browse files Browse the repository at this point in the history
  • Loading branch information
tg123 committed May 13, 2015
1 parent 262c8af commit b53d582
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
Empty file added course-schedule-ii/README.md
Empty file.
69 changes: 69 additions & 0 deletions course-schedule-ii/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
public class Solution {

static class Vertex {

int id;

Vertex(int id){
this.id = id;
}

Set<Integer> in = new HashSet<>();
Set<Integer> out = new HashSet<>();

boolean isSink(){
return out.isEmpty();
}
}

Vertex safe(Vertex[] G, int id){
if(G[id] == null){
G[id] = new Vertex(id);
}

return G[id];
}

public int[] findOrder(int numCourses, int[][] prerequisites) {
Vertex[] G = new Vertex[numCourses];

for(int[] p : prerequisites){
safe(G, p[0]).out.add(p[1]);
safe(G, p[1]).in.add(p[0]);
}

Set<Vertex> S = Arrays.stream(G)
.filter(v -> v != null)
.collect(Collectors.toSet());


LinkedHashSet<Integer> order = new LinkedHashSet<>(numCourses);

loop:
while(!S.isEmpty()){

for(Vertex v : S){
if(v.isSink()){
order.add(v.id);

S.remove(v);

for(int i : v.in){
G[i].out.remove(v.id);
}

continue loop;
}
}

return new int[]{};
}

// fill courses not in G
order.addAll(IntStream.range(0, numCourses).boxed().collect(Collectors.toSet()));

return order.stream()
.mapToInt(i -> i)
.toArray();
}
}
7 changes: 7 additions & 0 deletions course-schedule-ii/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
layout: solution
title: Course Schedule II
date: 2015-05-14 00:31:26+08:00
leetcode_id: 210
---
{% include_relative README.md %}

0 comments on commit b53d582

Please sign in to comment.