zoukankan      html  css  js  c++  java
  • 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求解

  • 相关阅读:
    Java泛型
    Java多态
    Anaconda+pycharm配置pytorch1.1.0+cuda 9.0+python3.7环境
    anaconda+fbprophet安装
    pycharm显示所有的tabs
    联想拯救者15-isk安装固态硬盘与系统迁移教程
    VS2017 C++操作mysql数据库
    mfc动态演示排序算法
    模拟处理机作业调度---短作业优先调度算法
    P3327 [SDOI2015]约数个数和
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4485902.html
Copyright © 2011-2022 走看看