关闭

LeetCode Course Schedule

标签: javaleetcodeTopology
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:

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

进行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

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