Course Schedule

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?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

 

思路:即判断该图是否是有向无环图,或是否存在拓扑排序。

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        
        int[] degree = new int[numCourses];//每个定点的入度
        Stack<Integer> stack = new  Stack<Integer>();//存放入度为0的顶点
        List<Integer>[] adjList = new ArrayList[numCourses];//邻接表
        for(int q=0;q<numCourses;q++) adjList[q] = new ArrayList<Integer>();
        
        //初始化邻接表
        for(int p=0;p<prerequisites.length;p++) {
           adjList[prerequisites[p][1]].add(prerequisites[p][0]);
        }
        
        //初始化每个顶点入度
        for(int i=0;i<numCourses;i++) {
            for(Integer vertex:adjList[i])
            degree[vertex]++;
        }
        //将入度为0的顶点入栈
        for(int j=0;j<numCourses;j++) {
            if(degree[j]==0) stack.push(j);
        }
        
        int count = 0;//当前拓扑排序顶点个数
        while(!stack.empty()) {
            count++;
            int v = stack.pop();
            for(Integer i:adjList[v]) {
                if(--degree[i]==0) stack.push(i);
            }
        }
        if(count!=numCourses) return false;
        else return true;
    }
}

 当然也可以通过DFS或者BFS求解

posted @ 2015-05-07 20:09  mrpod2g  阅读(158)  评论(0编辑  收藏  举报