Leetcode 207. Course Schedule 210. Course Schedule II

来源:互联网 发布:iphone刷机后数据恢复 编辑:程序博客网 时间:2024/06/08 13:12

Leetcode 207. Course Schedule 


import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;public class Solution {    public boolean canFinish(int numCourses, int[][] prerequisites) {if(numCourses<=1)  return true;int[] degree = new int[numCourses];//  linkedgraph constructList<Set<Integer>> graph = new ArrayList<Set<Integer>>();    for(int i=0;i<numCourses;i++) graph.add(new HashSet<Integer>());    for(int[] edge:prerequisites){    degree[edge[0]]++;    graph.get(edge[1]).add(edge[0]);    }        //early queue;    Queue<Integer> queue = new LinkedList();     //List<Integer> early = new ArrayList<Integer>();                for(int i=0;i<numCourses;i++){    if(degree[i]==0)   queue.offer(i);    //degree[i] = graph.get(i).size();    }    int count=0;        while(!queue.isEmpty()){    int curr = queue.poll();    //res[count] = curr;    for(int j: graph.get(curr)){    if(--degree[j]==0)  {    queue.offer(j);    }    }    count++;    }        if(count==numCourses)   return true;    else{    return false;    }                }    }



210. Course Schedule II


public class Solution {public int[] findOrder(int numCourses, int[][] prerequisites) {int[] res = new int[numCourses];if(numCourses<=1)  return res;int[] degree = new int[numCourses];//  linkedgraph constructList<Set<Integer>> graph = new ArrayList<Set<Integer>>();    for(int i=0;i<numCourses;i++) graph.add(new HashSet<Integer>());    for(int[] edge:prerequisites){    degree[edge[0]]++;    graph.get(edge[1]).add(edge[0]);    }        //early queue;    Queue<Integer> queue = new LinkedList();     //List<Integer> early = new ArrayList<Integer>();                for(int i=0;i<numCourses;i++){    if(degree[i]==0)   queue.offer(i);    //degree[i] = graph.get(i).size();    }    int count=0;        while(!queue.isEmpty()){    int curr = queue.poll();    if(count>numCourses-1){    count++;    break;    }    res[count] = curr;    for(int j: graph.get(curr)){    if(--degree[j]==0)  {    queue.offer(j);    }    }    count++;    }        if(count==numCourses)   return res;    else{    return new int[0];    }                }}

bfs  一般采用queue结构来进行编写





0 0