# LeetCode Course Schedule

Description:

here 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.

Solution:

1. 先找入度为1的点，如果找不到，就返回false

2. 找到某一个入度为0的点，将所有从这个点能出发到的边遍历，每条边的另一个点入度都减去1

3. 如此循环n次

import java.util.*;

public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int n = numCourses;

int indegree[] = new int[n];
int mat[][] = new int[n][n];

for (int l = 0; l < prerequisites.length; l++) {
int i = prerequisites[l][0];
int j = prerequisites[l][1];
if (mat[i][j] == 1)
continue;
mat[i][j] = 1;
indegree[j]++;
}

int index;
for (int l = 0; l < n; l++) {
index = -1;
for (int i = 0; i < n; i++)
if (indegree[i] == 0) {
indegree[i] = -1;
index = i;
break;
}
if (index == -1)
return false;
for (int j = 0; j < n; j++)
if (mat[index][j] == 1)
indegree[j]--;
}

return true;
}
}

#### 【LeetCode】207. Course Schedule

2016-05-30 23:40:09

#### Leetcode 207 Course Schedule 课程表

2015-08-10 18:05:39

#### leetcode 207: Course Schedule

2015-05-20 05:07:51

#### 【LeetCode】Course Schedule 解题报告

2015-05-19 17:05:08

#### [leetcode-207]Course Schedule（java）

2015-08-26 15:23:03

#### leetcode 210: Course Schedule II

2015-05-22 07:15:55

#### [LeetCode]207. Course Schedule 课程表

2018-03-03 21:52:47

#### 课程调度问题：LeetCode 630. Course Schedule III

2017-06-26 14:19:47

#### 【LeetCode】Course Schedule II 解题报告

2015-05-19 17:13:08

#### LeetCode 207 - Course Schedule

2015-05-07 02:24:40