207. Course Schedule (Graph)
Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用
element()或者peek()方法。
初步了解BFS 用一个queue
题目中用edges的数组表达graph,可以用arraylist[]来组成比较方便使用的graph
1 class Solution { 2 public boolean canFinish(int numCourses, int[][] prerequisites) { 3 ArrayList[] graph = new ArrayList[numCourses]; 4 int[] degree = new int[numCourses]; 5 6 for(int i = 0; i < numCourses; i++) { 7 degree[i] = 0; 8 graph[i] = new ArrayList<>(); //每个arraylist都要new一下 9 } 10 11 for(int i = 0; i < prerequisites.length; i++) { 12 degree[prerequisites[i][0]]++; 13 graph[prerequisites[i][1]].add(prerequisites[i][0]); 14 } 15 int count = 0; 16 Queue queue = new LinkedList<>(); 17 for(int i = 0; i < numCourses; i++) { 18 if(degree[i] == 0) { 19 count++; 20 queue.offer(i); 21 } 22 } 23 while(queue.size() != 0) { 24 int a = (int)queue.poll(); 25 queue.remove(a); 26 for(Object i : graph[a]) { 27 int b = (int)i; 28 degree[b]--; 29 if(degree[b] == 0) { 30 count++; 31 queue.offer(b); 32 } 33 34 } 35 } 36 return count == numCourses; 37 38 } 39 }