码迷,mamicode.com
首页 > 其他好文 > 详细

Course Schedule

时间:2015-05-07 21:47:35      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

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求解

Course Schedule

标签:

原文地址:http://www.cnblogs.com/mrpod2g/p/4485902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!