Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created May 17, 2020 22:48
Show Gist options
  • Save shixiaoyu/63a2e71566126a3dd43d49b2021f4347 to your computer and use it in GitHub Desktop.
Save shixiaoyu/63a2e71566126a3dd43d49b2021f4347 to your computer and use it in GitHub Desktop.
private class Node {
public int val;
public List<Node> neighbors;
public Node(int val) {
this.val = val;
this.neighbors = new ArrayList<>();
}
}
private List<Node> buildGraph(int num, int[][] prerequisites) {
List<Node> graph = new ArrayList<>();
for (int i = 0; i < num; i++) {
graph.add(new Node(i));
}
for (int i = 0; i < prerequisites.length; i++) {
graph.get(prerequisites[i][0]).neighbors.add(graph.get(prerequisites[i][1]));
}
return graph;
}
// model to a Nodes, still BFS with topological order to detect if a graph is a DAG
// https://www.geeksforgeeks.org/detect-cycle-in-a-directed-graph-using-bfs/
public boolean canFinishGraph(int numCourses, int[][] prerequisites) {
if (numCourses <= 1 || prerequisites.length == 0 || prerequisites[0].length == 0) {
return true;
}
List<Node> graph = this.buildGraph(numCourses, prerequisites);
Queue<Node> q = new LinkedList<>();
for (Node n : graph) {
if (n.neighbors.size() == 0) {
q.add(n);
}
}
Set<Node> visited = new HashSet<>();
while (!q.isEmpty()) {
Node cur = q.poll();
visited.add(cur);
for (Node n : graph) {
if (n.neighbors.contains(cur)) {
n.neighbors.remove(cur);
// only enqueue the nodes while there is no more neighbors
if (n.neighbors.size() == 0) {
q.add(n);
}
}
}
}
return visited.size() == numCourses;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment