[백준 알고리즘] Node.js 11403. 경로 찾기

2023. 7. 26. 16:15코딩연습

1. 문제

https://www.acmicpc.net/problem/11403

 

11403번: 경로 찾기

가중치 없는 방향 그래프 G가 주어졌을 때, 모든 정점 (i, j)에 대해서, i에서 j로 가는 길이가 양수인 경로가 있는지 없는지 구하는 프로그램을 작성하시오.

www.acmicpc.net

 

2. 풀이

- 플로이드-와샬(Floyd Warshall) 알고리즘을 이용하여 푸는 문제였다.

const [N, ...inputs] = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const graph = inputs.map((input) => {
    return input.split(' ').map(v => +v);
})

for(let k = 0; k < N; k++){
    for(let i = 0; i < N; i++){
        for(let j = 0; j < N; j++){
            if(graph[i][k] === 1 && graph[k][j] === 1) graph[i][j] = 1;
        }
    }
}

let result = "";
for(const item of graph){
    result += `${item.join(" ")}\n`;
}
console.log(result)

 

3. 정리

- 플로이드 와샬(Floyd Warshall) 알고리즘이란?