KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (487)
    • 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 (432)
      • 백준 (187)
      • Programmers (105)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

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

공지사항

인기 글

태그

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

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/백준

백준 / 그래프 / 11404번 / 플로이드 / JS

2024. 7. 12. 17:07

문제 간단설명

n(2 ≤ n ≤ 100)개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 m(1 ≤ m ≤ 100,000)개의 버스가 있다. 각 버스는 한 번 사용할 때 필요한 비용이 있다.

모든 도시의 쌍 (A, B)에 대해서 도시 A에서 B로 가는데 필요한 비용의 최솟값을 구하는 프로그램을 작성하시오.

 

제한 사항

  • 2 <= n <= 100
  • 1 <= m <= 100,000
  • 1 <= c <= 100,000
  • 시작 도시와 도착 도시를 연결하는 노선은 하나가 아닐 수 있다.

 

성공 코드

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : '../input.txt';
// const filePath = process.platform === 'linux' ? '/dev/stdin' : 'BOJ/input.txt';
const input = fs.readFileSync(filePath).toString().trim().split('\n');

const n = +input.shift();
const m = +input.shift();
const busList = input.map((row) => row.split(' ').map(Number));

const solution = () => {
  const adjMatrix = Array.from({ length: n + 1 }, () =>
    Array.from({ length: n + 1 }, () => Infinity)
  );

  /**
   * 인접행렬을 만드는 함수이다.
   */
  const initAdjMatrix = () => {
    for (const [start, end, cost] of busList) {
      adjMatrix[start][end] = Math.min(adjMatrix[start][end], cost);
    }

    for (let i = 1; i <= n; i++) {
      for (let j = 1; j <= n; j++) {
        // 자기자신으로 가는 비용은 0으로 초기화해준다.
        if (i === j) {
          adjMatrix[i][j] = 0;
        }
      }
    }
  };

  /**
   * Floyd-Warshall 알고리즘으로 최단거리를 구하는 함수이다.
   */
  const floydWarshall = () => {
    for (let k = 1; k <= n; k++) {
      for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= n; j++) {
          if (adjMatrix[i][j] > adjMatrix[i][k] + adjMatrix[k][j]) {
            adjMatrix[i][j] = adjMatrix[i][k] + adjMatrix[k][j];
          }
        }
      }
    }
  };

  /**
   * 정답을 주어진 형식에 맞게 출력하는 함수이다.
   */
  const printResult = () => {
    for (let i = 1; i <= n; i++) {
      const row = [];
      for (let j = 1; j <= n; j++) {
        if (adjMatrix[i][j] === Infinity) {
          row.push(0);
        } else {
          row.push(adjMatrix[i][j]);
        }
      }

      console.log(row.join(' '));
    }
  };

  initAdjMatrix();
  floydWarshall();
  printResult();
};

solution();
저작자표시 (새창열림)

'PS > 백준' 카테고리의 다른 글

백준 / 그래프 / 14940번 / 쉬운 최단거리 / JS  (0) 2024.11.06
백준 / 재귀 / 12919번 / A와 B 2 / JS  (1) 2024.10.24
백준 / 비트마스킹 / 11723번 / 집합 / JS  (1) 2024.07.05
백준 / 그래프 / 2667번 / 단지번호붙이기 / JS  (1) 2023.12.25
    'PS/백준' 카테고리의 다른 글
    • 백준 / 그래프 / 14940번 / 쉬운 최단거리 / JS
    • 백준 / 재귀 / 12919번 / A와 B 2 / JS
    • 백준 / 비트마스킹 / 11723번 / 집합 / JS
    • 백준 / 그래프 / 2667번 / 단지번호붙이기 / JS
    KimMinJun
    KimMinJun

    티스토리툴바