LeetCode#210

Course Schedule II

Posted by Start Bootstrap on February 16, 2020 · 3 mins read

문제

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.

0부터 n-1까지 라벨이 붙은 총 n개의 코스가 있다.

일부 과정에는 선행 조건이 있을 수 있다. 예를 들어, 0코스를 수강하려면 먼저 코스 1을 수강해야 한다. [0,1]

총 과정 수와 필수 과정 쌍 목록을 고려하여 모든 과정을 마치려면 수강해야 하는 과정 순서를 반환하십시오.

순서가 여러 개 있을 수 있으니 한 개만 돌려주면 된다. 모든 과정을 완료할 수 없는 경우 빈 배열을 반환하십시오.

Example 1:

Input: 2, [[1,0]] 
Output: [0,1]
Explanation: 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] .

Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: 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] .

Note :

1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
2. You may assume that there are no duplicate edges in the input prerequisites.

기본 지식

이번 문제는 “위상 정렬” 문제의 연장선으로 Leetcode#207글을 먼저 봐주시면 감사하겠습니다.

풀이

class Solution {   
        public int[] findOrder(int numCourses, int[][] prerequisites){
            int[] indegree = new int[numCourses];
            int[] ret = new int[numCourses];
            List<List<Integer>> adjList = new ArrayList<>();
            for(int i=0; i<numCourses; i++){
                adjList.add(new ArrayList<Integer>());
            }
            
            for(int[] edge: prerequisites){
                indegree[edge[0]]++;
                adjList.get(edge[1]).add(edge[0]);
            }
            
            Queue<Integer> q = new LinkedList<>();
            for(int i=0; i<numCourses; i++){
                if(indegree[i]==0) q.offer(i);
            }
            
            int idx = 0;
            
            while(!q.isEmpty()){
                int node = q.poll();
                ret[idx++] = node;
                for(int dest:adjList.get(node)){
                    if(--indegree[dest]==0) q.offer(dest);
                }
                adjList.get(node).clear();
            }
            
            return idx == numCourses?ret:new int[0];
        }
    
}

Leetcode#207에서 방문하는 노드를 ret 배열에 입력하는 내용만 추가되었을 뿐입니다.

idx == numCourses 가 true일 경우, 모든 과정을 수강할 수 있다는 뜻으로 ret 배열(과정의 순서)를 return하고 false일 경우 빈배열(int[0])을 return 합니다.

출처 : 제가 알고리즘 문제에 막 감을 익히고 있는 단계여서 유튜버 승지니어님의 코드를 인용하였습니다. 도움되는 영상이 많이 있으므로 많은 방문 부탁드리겠습니다.

유튜브 승지니어 해당영상