LeetCode OJ 207. Course Schedule 拓扑排序+邻接表

    题目链接:https://leetcode.com/problems/course-schedule/

207. Course Schedule

 

My Submissions Question Editorial Solution
Total Accepted: 42752 
Total Submissions: 154752 
Difficulty: Medium

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

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

click to show more hints.

Subscribe to see which companies asked this question

Show Tags Show Similar Problems
Have you met this question in a real interview? 

Yes   No

Discuss Pick One

    这是一道图论的题目,考察的是拓扑排序。拓扑排序需要邻接表存储图。四年没用邻接表了,复习了下邻接表再来做的这个题目。

    拓扑排序的思路:

  1. 入度为0的顶点入队列
  2. 队列每出一个顶点,这个顶点所有边的另一头元素的入度减一。如果入度减到0了,入队列。
  3. 循环第二步,直至队列为空。

    我的AC代码:

package march;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * Created by Administrator on 2016/6/17.
 */
public class CourseSchedule {

	public static void main(String[] args) {
		CourseSchedule cs = new CourseSchedule();
		int[][]        a  = {{0, 1}};
		System.out.println(cs.canFinish(2, a));
		int[][] b = {{0, 1}, {1, 0}};
		System.out.println(cs.canFinish(2, b));
	}

	public boolean canFinish(int numCourses, int[][] prerequisites) {
		Edge[]    edges   = new Edge[numCourses];
		int[]     indgree = new int[numCourses];
		boolean[] visited = new boolean[numCourses];
		for (int i = 0; i < numCourses; i++) edges[i] = new Edge(-1);

		for (int i = 0; i < prerequisites.length; i++) {
			int[] edge = prerequisites[i];
			Edge e = new Edge(edge[1]);
			int edgeHead = edge[0];
			e.next = edges[edgeHead].next;
			edges[edgeHead].next = e;

			indgree[edge[1]]++;
		}
		Queue<Integer> q = new ArrayDeque<Integer>(numCourses);
		for (int i = 0; i < numCourses; i++) {
			if (indgree[i] == 0) q.add(i);
		}
		if (q.isEmpty()) return false;

		while (!q.isEmpty()) {
			int ver = q.poll();
			visited[ver] = true;
			Edge head = edges[ver].next;
			while (head != null) {
				if (--indgree[head.num] == 0) q.add(head.num);
				head = head.next;
			}
		}

		boolean result = true;
		for (boolean v : visited) result &= v;
		return result;
	}
}

class Edge {
	public Edge(int n) {
		num = n;
	}

	public int num;
	public Edge next = null;
}
    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/bruce128/article/details/51699998
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞