[LeetCode]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.


思路

这道题目是典型的图的拓扑排序题目,这里先简要介绍一下拓扑排序算法的实现步骤:

  1. 初始化图邻接矩阵(u依赖于于v,则matrix[u][v]==1)和每个节点的入度数组(u依赖于v,则indegree[v]++)。
  2. 从入度数组中选取一个没有前驱节点(即indegree[v]==0)的顶点输出。
  3. 从图中删除该顶点和所有以它为头节点的弧。(即所有matrix[v][otherV]==1的,indegre[otherV]–)。
  4. 重复2,3步骤,直到全部顶点均已输出,或者图中不存在无前驱的顶点为止.(此时说明图中有环)。

所以,这道题目就是检测最后构造的图中是否有环即可(即检测indegree数组是否有顶点的值大于0)。


AC Code

ac代码如下所示:

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        boolean canFinish = true;
        int[] indegree = new int[numCourses];
        int[][] matrix = new int[numCourses][numCourses];

        // initial data
        for (int i = 0; i < prerequisites.length; i ++) {
            if (matrix[prerequisites[i][0]][prerequisites[i][1]] == 1) continue;
            indegree[prerequisites[i][1]] ++;
            matrix[prerequisites[i][0]][prerequisites[i][1]] = 1;
        }

        // topological sort
        for (int i = 0; i < numCourses; i ++) {
            for (int j = 0; j < numCourses; j ++) {
                if (indegree[j] == 0) {
                    indegree[j] --;

                    // delete node which start is j
                    for (int k = 0; k < numCourses; k ++) {
                        if (matrix[j][k] == 1) {
                            indegree[k] --;
                            matrix[j][k] = 0;
                        }
                    }

                    break;
                }
            }
        }

        // output result
        for (int i = 0; i < numCourses; i ++) {
            if (indegree[i] > 0) {
                canFinish = false;
                break;
            }
        }   

        return canFinish;
    }
}
时间: 2024-10-15 04:59:26

[LeetCode]Course Schedule,解题报告的相关文章

LeetCode: Combination Sum 解题报告

Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Question Solution Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The

[LeetCode]LRU Cache, 解题报告

题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

poj 1325 Machine Schedule 解题报告

题目链接:http://poj.org/problem?id=1325 题目意思:有 k 个作业,机器A有 n 个模式:0 ~ n-1,机器B 有 m 个模式:0~ m-1.每一个作业能运行在 A 的 某一个模式(假设为 i (0 <= i <= n-1 ) )或 B 的某一个模式下(j (0 <= j <= m-1)).多个作业可以同时运行在 A 的某一个 模式下,当然 B 也如此.每对A 或 B 转换一次模式,就要重启一次 A 或者 B,你需要选择A 或 B 的一些模式,使得所

【LeetCode】Subsets 解题报告

[题目] Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,

【LeetCode】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 an

LeetCode ZigZag Conversion 解题报告

对输入字符串,做蛇形变化,然后按行输出. https://oj.leetcode.com/problems/zigzag-conversion/ 例如:The string "PAYPALISHIRING"  的蛇形变化如下: P        A           H        N A   P   L    S     I     I   G Y         I            R 最后要求输出的就是:"PAHNAPLSIIGYIR" Write

LeetCode: Gas Station 解题报告

Gas Station There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journ

Leetcode:Interleaving String 解题报告

Interleaving StringGiven s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = "aabcc",s2 = "dbbca", When s3 = "aadbbcbcac", return true.When s3 = "aadbbbaccc", return false.

Leetcode:Scramble String 解题报告

Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / gr eat / \ / g r e at / a t To scramble the string,

LeetCode: Merge Intervals 解题报告

Merge IntervalsGiven a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,10],[15,18],return [1,6],[8,10],[15,18]. SOLUTION 1: 1. 先使用Comparator 的匿名类对intervels进行排序. 2. 把Intervals遍历一次,依次一个一个merge到第1个interval. 把第1