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

Course Schedule 题解

时间:2015-05-15 21:33:24      阅读:225      评论: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.

解析

这是一个典型的拓扑排序,判断是否存在环,如果0->1(学1前要学0),并且1->0,则输出false

public static boolean canFinish(int numCourses, int[][] prerequisites) {
        boolean canFinish = true;
        int[] indegree = new int[numCourses];//用来存放第i个结点的入度
        int[][] matrix = new int[numCourses][numCourses];//matrix[i][j],i->j,i是j的先行课

        Stack<Integer> stack = new Stack<Integer>();
        // 初始化邻接表
        for (int i = 0; i < prerequisites.length; i++) {
            if (matrix[prerequisites[i][1]][prerequisites[i][0]] == 1)
                continue;
            indegree[prerequisites[i][0]]++;
            matrix[prerequisites[i][1]][prerequisites[i][0]] = 1;
        }

        //将入度为0的结点入栈
        for(int i=0;i<numCourses;i++){
            if(indegree[i]==0)
                stack.push(i);
        }
        //将入度为0的结点出栈,且将以此节点为条件的结点的入度-1,并将此时为0的结点入栈,直到栈为空
        while(stack.size()>0){
            int node = stack.pop();
            for (int k = 0; k < numCourses; k++) {
                if (matrix[node][k] == 1) {
                    indegree[k]--;
                    matrix[node][k] = 0;
                    if(indegree[k]==0){
                        stack.push(k);
                    }
                }
            }
        }

        //统计是否含有入读大于0的结点
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] > 0) {
                canFinish = false;
                break;
            }
        }

        return canFinish;
    }

Course Schedule 题解

标签:

原文地址:http://blog.csdn.net/tule_ant/article/details/45748553

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