[PS] Leet | 207. 과목 스케쥴

2025. 4. 19. 19:47·CS/PS

문제

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [a_i, b_i] indicates that you must take course b_i first if you want to take course a_i.

For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.

예시

Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take. 
To take course 1 you should have finished course 0. So it is possible.


Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: 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.

조건

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.

답

Directed graph의 형태로, 순환구조가 존재하는지 확인하는 문제입니다.

 

최상단의 그래프 노드(prerequiste이 존재하지 않는)들로 queue를 구성하여 BFS를 수행합니다.

 

탐색하는 각 노드와 연결된 노드들의 indegree를 하나씩 감소시키면서, indegree가 0이 되는 노드(=모든 prerequiste을 수강한 과목)가 있으면 queue에 추가시킵니다.

 

queue가 모두 빌 때 까지 반복하며, 탐색한 노드 수가 전체 과목수와 같다면 모두 수강 가능 한 것으로 판단할 수 있습니다.

/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {boolean}
 */
var canFinish = function(numCourses, prerequisites) {
    const graph = Array.from({length: numCourses}, () => []);
    const indegree = new Array(numCourses).fill(0);
    const queue = [];
    let remainingCourses = numCourses;

    for (const edge of prerequisites) {
        graph[edge[1]].push(edge[0]);
        indegree[edge[0]]++;
    }

    for (let i=0; i<numCourses; ++i) {
        if (indegree[i] === 0) queue.push(i);
    }

    while (queue.length > 0) {
        const current = queue.shift();
        remainingCourses--;
        
        for (const course of graph[current]){
            indegree[course]--;
            if (indegree[course] === 0) queue.push(course);
        }
    }

    return remainingCourses === 0;
};

numCourse = n, prerequistes.length = m 일 때,

 

시간 복잡도 : O(n+m)

공간 복잡도 : O(n+m)

728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 57. 구간 삽입  (0) 2025.04.26
[PS] Leet | 128. 가장 긴 연속 수  (0) 2025.04.24
[PS] Leet | 133. 그래프 복사  (0) 2025.04.11
[PS] Leet | 213. 빈집 털이 II  (0) 2025.04.10
[PS] Leet | 1143. 가장 긴 공통 배열  (0) 2025.04.05
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 57. 구간 삽입
  • [PS] Leet | 128. 가장 긴 연속 수
  • [PS] Leet | 133. 그래프 복사
  • [PS] Leet | 213. 빈집 털이 II
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    deploy
    PyTorch
    GAN
    html
    frontend
    js
    ML
    mongo
    nodejs
    CSS
    C++
    Express
    react
    SOLID
    python
    DB
    PRISMA
    UI
    review
    ts
    CS
    CV
    backend
    API
    Three
    vscode
    ps
    postgresql
    figma
    Git
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 207. 과목 스케쥴
상단으로

티스토리툴바