[url]https://leetcode.com/problems/course-schedule/[/url]
[分析] 典型的拓扑排序应用。先根据课程的先修关系构造一个graph,graph中的节点数==课程数,先修关系pair代表graph中的一条边,注意测试case中先修关系有重复,因此仅当创建新边时才更新相应节点的indegree。
[分析] 典型的拓扑排序应用。先根据课程的先修关系构造一个graph,graph中的节点数==课程数,先修关系pair代表graph中的一条边,注意测试case中先修关系有重复,因此仅当创建新边时才更新相应节点的indegree。
public class Solution {
// method 2: 二维数组表示有向图
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites == null || prerequisites.length == 0 || prerequisites[0].length == 0)
return true;
// build graph
ArrayList<HashSet<Integer>> graph = new ArrayList<HashSet<Integer>>(numCourses);
int[] indegree = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
graph.add(new HashSet<Integer>());
}
int m = prerequisites.length;
for (int i = 0; i < m; i++) {
if (graph.get(prerequisites[i][0]).add(prerequisites[i][1]))
indegree[prerequisites[i][1]]++;
}
// check
LinkedList<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) queue.offer(i);
}
int counter = 0;
while (!queue.isEmpty()) {
counter++;
int curr = queue.poll();
for (int w : graph.get(curr)) {
if (--indegree[w] == 0) queue.offer(w);
}
}
return counter == numCourses;
}
// method 1
class Vertex {
int value;
int indegree;
HashSet<Vertex> adjacent;
public Vertex(int val) {
this.value = val;
indegree = 0;
adjacent = new HashSet<Vertex>();
}
}
public boolean canFinish1(int numCourses, int[][] prerequisites) {
if (prerequisites == null || prerequisites.length == 0 || prerequisites[0].length == 0)
return true;
HashMap<Integer, Vertex> graph = buildGraph(numCourses, prerequisites);
LinkedList<Vertex> queue = new LinkedList<Vertex>();
for(Vertex node : graph.values()) {
if (node.indegree == 0)
queue.offer(node);
}
int counter = 0;
while (!queue.isEmpty()) {
Vertex node = queue.poll();
counter++;
for (Vertex w : node.adjacent) {
w.indegree--;
if (w.indegree == 0) queue.offer(w);
}
}
return counter == graph.size();
}
private HashMap<Integer, Vertex> buildGraph(int numCourses, int[][] prerequisites) {
HashMap<Integer, Vertex> graph = new HashMap<Integer, Vertex>();
for (int i = 0; i < numCourses; i++) {
graph.put(i, new Vertex(i));
}
int m = prerequisites.length;
for (int i = 0; i < m; i++) {
if(graph.get(prerequisites[i][0]).adjacent.add(graph.get(prerequisites[i][1]))) {
graph.get(prerequisites[i][1]).indegree++;
}
}
return graph;
}
}