lintcode(615)Course Schedule

来源:互联网 发布:iphone中的照片导入mac 编辑:程序博客网 时间:2024/06/06 09:03

Description:

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Explanation:

Given n = 2, prerequisites = [[1,0]]
Return true

Given n = 2, prerequisites = [[1,0],[0,1]]
Return false

Solution;

ArrayList<HashSet<Integer>>

If finish

Then finish (HashSet) 

0

{1,2}

1

{3}

2

{3}

3

{}

Int[] numPre

course

Number of preRequireCoures

0

1

1

2

1

3

2

Go through the array prerequisites torecord the course and its followers (if we have finished a, then we can finishb. Push b to HashSet of a). Then record the number of previous required courses(PRC)of each course. If the number is zero, then push it to the sorted courses. Thenwe need to poll out the class and record it in the result, when  poll out one course, renew the number of PRC ofthe related course , then check whether it can be offer to the queue. Go againthe last operation until the sorted courses is empty.  

public class Solution {    /**     * @param numCourses a total of n courses     * @param prerequisites a list of prerequisite pairs     * @return true if can finish all courses or false     */    public boolean canFinish(int numCourses, int[][] prerequisites) {        // Write your code here        ArrayList<HashSet<Integer>> record = new ArrayList<HashSet<Integer>>();        for(int i = 0;i<numCourses;i++){            record.add(new HashSet<Integer>());        }                for(int i = 0;i<prerequisites.length;i++){            record.get(prerequisites[i][1]).add(prerequisites[i][0]);        }                int[] numPre = new int[numCourses];        for(int i = 0;i<numCourses;i++){            for(int after : record.get(i)){                numPre[after]++;            }        }                Queue<Integer> sortCourse = new LinkedList<Integer>();        for(int i = 0;i<numCourses;i++){            if(numPre[i] == 0){                sortCourse.offer(i);            }        }        int count = 0;        while(!sortCourse.isEmpty()){            int current = sortCourse.poll();            for(int after : record.get(current)){                numPre[after]--;                if(numPre[after] == 0){                    sortCourse.offer(after);                }            }            count++;        }        return count == numCourses ? true : false;    }}


原创粉丝点击