# LeetCode Course Schedule

79人阅读 评论(0)

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;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：67086次
• 积分：3298
• 等级：
• 排名：第10603名
• 原创：288篇
• 转载：0篇
• 译文：0篇
• 评论：4条
文章分类
阅读排行
最新评论