Skip to content

Commit b1509e6

Browse files
committed
add: 백준/특정 거리의 도시 찾기
1 parent c21d62d commit b1509e6

1 file changed

Lines changed: 95 additions & 0 deletions

File tree

boj/18352(다익스트라).js

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// 특정 거리의 도시 찾기
2+
// https://www.acmicpc.net/problem/18352
3+
4+
function dijkstra(N, K, X, graph) {
5+
const visit = Array(N + 1).fill(Infinity);
6+
const queue = [];
7+
8+
queue.push([X, 0]);
9+
10+
visit[X] = 0;
11+
12+
while (queue.length !== 0) {
13+
queue.sort((a, b) => {
14+
return a[1] - b[1];
15+
});
16+
17+
const [vertex, weight] = queue.shift();
18+
19+
if (weight > K) {
20+
continue;
21+
}
22+
23+
for (let i = 0; i < graph[vertex].length; i++) {
24+
if (weight + 1 < visit[graph[vertex][i]]) {
25+
visit[graph[vertex][i]] = weight + 1;
26+
queue.push([graph[vertex][i], weight + 1]);
27+
}
28+
}
29+
}
30+
31+
const answer = [];
32+
33+
for (let i = 0; i < visit.length; i++) {
34+
if (visit[i] === K) {
35+
answer.push(i);
36+
}
37+
}
38+
39+
if (answer.length === 0) {
40+
return '-1';
41+
}
42+
43+
return answer.join('\n');
44+
}
45+
46+
const fs = require('fs');
47+
const stdin = (process.platform === 'linux'
48+
? fs.readFileSync('/dev/stdin').toString().trim()
49+
: `4 4 1 1
50+
1 2
51+
1 3
52+
2 3
53+
2 4
54+
`
55+
).split('\n');
56+
57+
const input = (() => {
58+
let line = 0;
59+
return () => stdin[line++];
60+
})();
61+
62+
const [N, M, K, X] = input()
63+
.split(' ')
64+
.map((each) => parseInt(each));
65+
66+
const graph = Array(N + 1);
67+
68+
for (let i = 0; i < graph.length; i++) {
69+
graph[i] = [];
70+
}
71+
72+
for (let i = 0; i < M; i++) {
73+
const [A, B] = input()
74+
.split(' ')
75+
.map((each) => parseInt(each));
76+
77+
graph[A].push(B);
78+
}
79+
80+
console.log(dijkstra(N, K, X, graph));
81+
82+
/*
83+
84+
## How
85+
다익스트라 문제이다. 일단 다익스트라에 대해서 정리가 안되어있어서 개념부터 다시 보았다.
86+
87+
다익스트라는 음의 가중치가 없는 그래프의 시작점에서 특정 노드까지 최단 거리를 구하는 알고리즘이다.
88+
89+
문제에서 가중치는 1로 동일했다. BFS와 유사하게 접근하면 된다. 다만 우선순위 큐를 사용해서 정점의 번호와 최단거리 pair를 enqueue한다.
90+
91+
자바스크립트에는 기본으로 제공되는 우선순위 큐 자료구조가 없어서 루프를 돌 때 마다 정렬하는 식으로 타협을 봤다.
92+
93+
## Retrospective
94+
95+
*/

0 commit comments

Comments
 (0)