개발하는 쿠키
article thumbnail

🚀 풀이 후기

이 문제를 풀다 보니 그래프에 순환이 있는지 파악하는 방법을 배우게 됐습니다.

선행 조건이 없는 노드들을 모두 제거한 후, 제거하지 못한 노드들이 있다면 순환 그래프입니다.

🌒 문제 설명

선행수업을 들어야 다음 수업을 들을 수 있습니다.

한 학기에는 여러 수업을 수강할 수 있습니다.

수업을 다 들을 수 있는 최소 학기 수를 반환하는 문제입니다.

만약 수업을 모두 들을 수 없다면 -1을 반환합니다.

You are given an integer n, which indicates that there are n courses labeled from 1 to n. 
You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], 
representing a prerequisite relationship between course prevCoursei and course nextCoursei: 
course prevCoursei has to be taken before course nextCoursei.

In one semester, you can take any number of courses 
as long as you have taken all the prerequisites in the previous semester for the courses you are taking.

Return the minimum number of semesters needed to take all courses. 
If there is no way to take all the courses, return -1.

Example 1 그림

Example 1:


Input: n = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation: The figure above represents the given graph.
In the first semester, you can take courses 1 and 2.
In the second semester, you can take course 3.

Example 2그림

Example 2:

Input: n = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation: No course can be studied because they are prerequisites of each other.
 

Constraints:

1 <= n <= 5000
1 <= relations.length <= 5000
relations[i].length == 2
1 <= prevCoursei, nextCoursei <= n
prevCoursei != nextCoursei
All the pairs [prevCoursei, nextCoursei] are unique.

 

🌓 문제 풀이

class Solution {
    public boolean[][] courseMap; // 선행해야 할 수업을 저장할 map
    public boolean[] finished; // 수강한 수업
    public int[] preCourseCnt; // 한 수업당 선행해야 하는 수업 개수
    public int completionCnt; // 수강한 수업 수
    public Queue<Integer> toTake; // 수강할 수업

    public int minimumSemesters(int n, int[][] relations) {
    	// 수업은 1부터 시작이므로 n+1 로 초기화합니다.
        courseMap = new boolean[n + 1][n + 1]; 
        preCourseCnt = new int[n + 1];
        finished = new boolean[n + 1];
        completionCnt = 0;
        toTake = new LinkedList<>();
        int rotate = 0;

        // 선행수업, 후행 수업 관계를 map에 저장합니다.
        courseMapInit(n, relations);
        
        while (true) {
            // 수강할 수업을 queue에 저장합니다.
            addCourse(n);
            
            // 수강할 수업이 없거나 수업을 모두 들었다면, while문을 나옵니다. 
            if (toTake.size() == 0 || completionCnt == n) {
                break;
            }
            
            // 수업을 수강합니다.
            takeCourse(n);
            
            // while문 반복 횟수를 늘립니다.
            rotate++;
        }
        // 답을 반환합니다.
        return getAnswer(rotate, completionCnt, n);
    }

    public void courseMapInit(int n, int[][] relations) {
        for (int[] relation : relations) {
            courseMap[relation[1]][relation[0]] = true; // [수강할 수업][들어야 할 수업] = true
            preCourseCnt[relation[1]]++; // 선행해야_할_수업_개수[수강할 수업]++
        }
        // printCourseMap();
    }

    public void addCourse(int n) {
        toTake.clear();
        for (int i = 1; i <= n; i++) {
        	// 해당 수업을 듣기 위해 선행해야 할 수업이 없고, 아직 들은 수업이 아니라면 toTake에 넣습니다.
            if (preCourseCnt[i] == 0 && !finished[i]) {
                toTake.add(i);
            }
        }
        // printToTake();
    }

    public void takeCourse(int n) {
        while (!toTake.isEmpty()) {
        	// 수업을 수강합니다. 
            int course = toTake.poll();
            completionCnt++; // 수강한 수업 개수 +1
            finished[course] = true; // 수업 수강 완료 체크

            for (int i = 1; i <= n; i++) {
                if (courseMap[i][course]) { // 수강한 수업이 선행수업이라면,
                    courseMap[i][course] = false; // 선행수업 제거
                    preCourseCnt[i]--; // 선행해야 할 수업 개수 -1
                }
            }

        }
    }

    public int getAnswer(int rotate, int completionCnt, int n) {
    	// 수강한 수업 개수가 n보다 작다면 순환그래프이므로 -1 을 반환합니다.
        if (completionCnt < n) {
            return -1;
        }
        
        // 수업을 모두 들었다면 while문 반복횟수를 반환합니다.
        return rotate;
    }

    public void printCourseMap() {
        for (boolean[] course : courseMap) {
            System.out.println(Arrays.toString(course));
        }
    }

    public void printToTake() {
        System.out.println(toTake);
    }
}

N: 노드 수 , M: 노드의 가지 수

- 시간복잡도:  O(N*M)

- 공간복잡도:  O(N^2)

 


리트코드 문제

깃허브 코드

반응형
profile

개발하는 쿠키

@COOKIE_

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!