공부기록

210. Course Schedule II 본문

코테/LeetCode

210. Course Schedule II

코타쿠 2022. 4. 8. 09:26

문제

https://leetcode.com/problems/course-schedule-ii/

코드

import java.util.*;

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<Integer> g[] = new List[numCourses];
        int dp[] = new int[numCourses];
        boolean visit[] = new boolean[numCourses];
        List<Integer> res = new ArrayList<>();
        Queue<Integer> q = new LinkedList<>();


        for(int i=0; i<g.length; i++)
            g[i] = new ArrayList<>();

        for(int i=0; i<prerequisites.length; i++){
            g[prerequisites[i][1]].add(prerequisites[i][0]);
            dp[prerequisites[i][0]]++;
        }

        for(int i=0; i<numCourses; i++){
            if(dp[i] == 0){
                visit[i] = true;
                q.add(i);
            }
        }

        while(!q.isEmpty()){
            int curNode = q.poll();
            res.add(curNode);
            for(int node : g[curNode])
                dp[node]--;
            for(int i=0; i<numCourses; i++){
                if(dp[i] == 0 && visit[i] == false){
                    visit[i] = true;
                    q.add(i);
                }
            }
        }

        for(int i=0; i<numCourses; i++)
            if(dp[i] != 0)
                return new ArrayList<Integer>().stream().mapToInt(Integer::intValue).toArray();

        System.out.println(res);

        return res.stream().mapToInt(Integer::intValue).toArray();

    }
}

피드백

'코테 > LeetCode' 카테고리의 다른 글

179. Largest Number  (0) 2022.04.15
384. Shuffle an Array  (0) 2022.04.09
240. Search a 2D Matrix II  (0) 2022.04.07
96. Unique Binary Search Trees  (0) 2022.03.21
242. Valid Anagram  (0) 2022.03.14