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)

블로그 메뉴

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

공지사항

인기 글

태그

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

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS

Topological Sort (위상 정렬)

2022. 5. 10. 23:09

 

/*
  이 알고리즘(위상정렬)이 사용된 백준 문제
  -> BOJ/Graph/2252.js
  -> BOJ/Graph/1516.js
  -> 줄 세우기
*/

const testInput = [
  [4, 2],
  [3, 1]
];

const N = 4; // 노드의 개수

function topological_sort() {
  let graph = Array.from({length: N + 1}, () => []);
  let indegrees = Array(N + 1).fill(0);
  let queue = [];
  let result = [];

  for(const [from, to] of testInput) {
    // from 노드와 이어져 있는 to 노드 추가
    graph[from].push(to);
    // to 노드와 이어져 있는 from 노드의 개수만큼 +1
    indegrees[to]++;
  }

  // inDegress가 0이라면 이전에 노드가 없는것이므로,
  // 시작 노드로 설정
  for(let i=1; i<indegrees.length; i++) {
    if(indegrees[i] === 0) queue.push(i);
  }

  while(queue.length) {
    const from = queue.shift();
    result.push(from);

    // from 노드로 부터 시작되는 다음 노드 순회
    for(const next of graph[from]) {
      // from 노드를 queue에서 빼냈으므로,
      // from 노드로 부터 시작되는 다음 노드의 indegree는 하나가 줄어듦
      indegrees[next]--;

	  // indegree를 하나 줄여주고 나서,
      // 0이면 queue에 넣어줌
      if(indegrees[next] === 0) queue.push(next);
    }
  }
  
  console.log(result.join(' '));
}

topological_sort();

 

 

 

GitHub - mj0107/algorithm-solving

Contribute to mj0107/algorithm-solving development by creating an account on GitHub.

github.com

 

저작자표시 (새창열림)
    KimMinJun
    KimMinJun

    티스토리툴바