-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path배달.js
69 lines (53 loc) · 1.43 KB
/
배달.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Solution 1
function solution1(N, road, K) {
const graph = Array.from({ length: N + 1 }, () => []);
const townsDistance = Array(N + 1).fill(Infinity);
road.forEach(([x, y, time]) => {
graph[x].push({
to: y,
time,
});
graph[y].push({
to: x,
time,
});
});
function bfs(start) {
const queue = [];
queue.push(start);
while (queue.length) {
const { to } = queue.shift();
graph[to].forEach((next) => {
if (townsDistance[next.to] > townsDistance[to] + next.time) {
townsDistance[next.to] = townsDistance[to] + next.time;
queue.push(next);
}
});
}
}
townsDistance[1] = 0;
bfs({ to: 1, time: 0 });
const townsCount = townsDistance.filter((time) => time <= K).length;
return townsCount;
}
// Solution 2
function solution2(N, road, K) {
const graph = Array.from({ length: N + 1 }, () => []);
const townsDistance = Array.from({ length: N + 1 }, () => Infinity);
road.forEach(([x, y, time]) => {
graph[x].push([y, time]);
graph[y].push([x, time]);
});
function dfs(townNum, totalTime) {
if (townsDistance[townNum] < totalTime) {
return;
}
townsDistance[townNum] = totalTime;
for (const [nextTownNum, time] of graph[townNum]) {
dfs(nextTownNum, totalTime + time);
}
}
dfs(1, 0);
const townsCount = townsDistance.filter((time) => time <= K).length;
return townsCount;
}