KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (486)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (431)
      • 백준 (187)
      • Programmers (104)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • 백준
  • js
  • 제코베 JS 100제
  • 수학
  • Level 2
  • C
  • 다이나믹 프로그래밍
  • 문자열
  • 정렬
  • string
  • recursion
  • programmers
  • Level 0
  • Level 1
  • 그래프
  • LeetCode
  • Level1
  • C++
  • tree
  • codeup

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Graph / 210번 / Course Schedule II / JS

2023. 5. 14. 00:45

< 문제 바로가기 >

 

Course Schedule II - LeetCode

Can you solve this real interview question? Course Schedule II - 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] = [ai, bi] indicates that you must take

leetcode.com

 

< 문제 간단설명 >

총 들어야할 강의의 수인 numCourses와 선행 강의의 쌍인 prerequisites가 주어진다.

예를 들어 numCourses = 2, prerequisites = [[1, 0]] 이면, 총 들어야할 강의의 수는 2개이고 1번 강의를 듣기 위해선 0번 강의를 선행으로 들어야 한다. 이런식으로 주어질 때 어떤 순서로 들을 수 있는지 순서를 반환한다. 만약 순서가 꼬인다던가 해서 모든 강의를 들을 수 없다면 빈 배열을 반환한다.

 

/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {number[]}
 */
var findOrder = function(numCourses, prerequisites) {
    let graph = {};
    // 진입 차수
    let inDegree = Array.from({ length: numCourses }, () => 0);

    // [들을 강의, 듣기 위해 선행해야할 강의]
    for(const [COURSE, PREV_COURSE] of prerequisites) {
      if(PREV_COURSE in graph) {
        graph[PREV_COURSE].push(COURSE);
      }
      else {
        graph[PREV_COURSE] = [COURSE];
      }
      // 들을 강의를 듣기 위해 선행해야할 강의 개수 + 1
      inDegree[COURSE] += 1;
    }

    let queue = [];
    inDegree.forEach((count, course) => {
      // 선행 강의가 0개일경우,
      // 즉 선행강의가 없어도 들을 수 있는 강의, 다른 강의를 듣기위해서만 존재하는 강의
      // 시작 강의
      if(count === 0) {
        queue.push(course);
      }
    });
    
    let result = [];
    while(queue.length) {
      let course = queue.shift();

      if(course in graph) {
        for(const NEXT_COURSE of graph[course]) {
          // queue에서 꺼낸 현재 강의가 선행 강의가 되는 강의들의 진입 차수 - 1
          inDegree[NEXT_COURSE] -= 1;
          // 진입 차수가 0이 된다면 다음 강의를 알기 위해 queue에 넣어줌
          if(inDegree[NEXT_COURSE] === 0) {
            queue.push(NEXT_COURSE);
          }
        }
      }

      result.push(course);
    }

    // result에 담겨있는 강의들이 총 강의의 개수와 맞지 않을 경우 불가능
    if(numCourses !== result.length) {
      result = [];
    }
    return result;
};
저작자표시

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

LeetCode / Dynamic Programming / 322번 / Coin Change / JS  (0) 2023.05.14
LeetCode / Dynamic Programming / 198번 / House Robber / JS  (0) 2023.05.14
LeetCode / Graph / 417번 / Pacific Atlantic Water Flow / JS  (0) 2023.04.29
LeetCode / Graph / 994번 / Rotting Oranges / JS  (0) 2023.04.29
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Dynamic Programming / 322번 / Coin Change / JS
    • LeetCode / Dynamic Programming / 198번 / House Robber / JS
    • LeetCode / Graph / 417번 / Pacific Atlantic Water Flow / JS
    • LeetCode / Graph / 994번 / Rotting Oranges / JS
    KimMinJun
    KimMinJun

    티스토리툴바