[LeetCode] Course Schedule solution report, leetcodeschedule

Source: Internet
Author: User
Tags set set

[LeetCode] Course Schedule solution report, leetcodeschedule

[Question]

There are a total of n courses you have to take, labeled from0Ton - 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 shoshould 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 shoshould have finished course 0, and to take course 0 you shoshould also have finished course 1. So it is impossible.

[Resolution]

Typical Topology Sorting. The principle is also very simple. In a directed graph, each time a node without a precursor node is found (that is, a node with an inbound degree of 0), the edge pointing to other nodes is removed, repeat this process (BFS) until all nodes are found or no matching nodes exist (if a ring exists in the figure ).

Review one of the Three Representation Methods: edge representation (that is, the Representation Method in the question), the joining table method, and the joining matrix. It is easier to search for nodes with an inbound value of 0 by using the graph stored in an adjacent table.

[Java code]

public class Solution {    public boolean canFinish(int numCourses, int[][] prerequisites) {        // init the adjacency list        List<Set> posts = new ArrayList<Set>();        for (int i = 0; i < numCourses; i++) {            posts.add(new HashSet<Integer>());        }                // fill the adjacency list        for (int i = 0; i < prerequisites.length; i++) {            posts.get(prerequisites[i][1]).add(prerequisites[i][0]);        }                // count the pre-courses        int[] preNums = new int[numCourses];        for (int i = 0; i < numCourses; i++) {            Set set = posts.get(i);            Iterator<Integer> it = set.iterator();            while (it.hasNext()) {            preNums[it.next()]++;            }        }                // remove a non-pre course each time        for (int i = 0; i < numCourses; i++) {            // find a non-pre course            int j = 0;            for ( ; j < numCourses; j++) {                if (preNums[j] == 0) break;            }                        // if not find a non-pre course            if (j == numCourses) return false;                        preNums[j] = -1;                        // decrease courses that post the course            Set set = posts.get(j);            Iterator<Integer> it = set.iterator();            while (it.hasNext()) {            preNums[it.next()]--;            }        }                return true;    }}

Note that the input may have duplicate edges, so the adjacent table is stored in HashSet.

The following code does not use HashSet. For duplicate edges, it splits two copies in the adjacent table and calculates the inbound degree twice, so the code will not be faulty. But I personally think it is best to use HashSet to conform to the graph definition.

The following code is a typical BFS writing method, which can be compared and understood as follows:

public class Solution {    public boolean canFinish(int numCourses, int[][] prerequisites) {        List<List<Integer>> posts = new ArrayList<List<Integer>>();        for (int i = 0; i < numCourses; i++) {            posts.add(new ArrayList<Integer>());        }                int[] preNums = new int[numCourses];        for (int i = 0; i < prerequisites.length; i++) {            posts.get(prerequisites[i][1]).add(prerequisites[i][0]);            preNums[prerequisites[i][0]]++;        }                Queue<Integer> queue = new LinkedList<Integer>();        for (int i = 0; i < numCourses; i++) {            if (preNums[i] == 0){                queue.offer(i);            }        }                int count = numCourses;        while (!queue.isEmpty()) {            int cur = queue.poll();            for (int i : posts.get(cur)) {                if (--preNums[i] == 0) {                    queue.offer(i);                }            }            count--;        }                return count == 0;    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.