LeetCode Course Schedule

来源:互联网 发布:淘宝一件代发平台 编辑:程序博客网 时间:2024/06/05 02:37

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:

拓扑排序,先根据前置要求将图构建出来,同时记录每个点的入度。

进行n次循环,每次循环做下面的处理:

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