关闭

LeetCode Course Schedule II

标签: javaleetcodeTopology
140人阅读 评论(0) 收藏 举报
分类:

Description:

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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

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 the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

Solution:

Course Schedule一样,就是将拓扑的结果任意输出一个。然后发现一个bug,前面没注意到的,pre[i][0]是在pre[i][1]之后的意思……貌似方向搞反了

import java.util.*;

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

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

		for (int l = 0; l < prerequisites.length; l++) {
			int j = prerequisites[l][0];
			int i = 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 new int[0];
			topo[l] = index;
			for (int j = 0; j < n; j++)
				if (mat[index][j] == 1)
					indegree[j]--;
		}

		return topo;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:61501次
    • 积分:3253
    • 等级:
    • 排名:第10408名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论