N개의 마을로 이루어진 나라가 있습니다. 이 나라의 각 마을에는 1부터 N까지의 번호가 각각 하나씩 부여되어 있습니다. 각 마을은 양방향으로 통행할 수 있는 도로로 연결되어 있는데, 서로 다른 마을 간에 이동할 때는 이 도로를 지나야 합니다. 도로를 지날 때 걸리는 시간은 도로별로 다릅니다. 현재 1번 마을에 있는 음식점에서 각 마을로 음식 배달을 하려고 합니다. 각 마을로부터 음식 주문을 받으려고 하는데, N개의 마을 중에서 K 시간 이하로 배달이 가능한 마을에서만 주문을 받으려고 합니다. 다음은 N = 5, K = 3인 경우의 예시입니다.
위 그림에서 1번 마을에 있는 음식점은 [1, 2, 4, 5] 번 마을까지는 3 이하의 시간에 배달할 수 있습니다. 그러나 3번 마을까지는 3시간 이내로 배달할 수 있는 경로가 없으므로 3번 마을에서는 주문을 받지 않습니다. 따라서 1번 마을에 있는 음식점이 배달 주문을 받을 수 있는 마을은 4개가 됩니다.
마을의 개수 N, 각 마을을 연결하는 도로의 정보 road, 음식 배달이 가능한 시간 K가 매개변수로 주어질 때, 음식 주문을 받을 수 있는 마을의 개수를 return 하도록 solution 함수를 완성해주세요.
const solution2 = (N, road, K) => {
let answer = new Set();
let graph = Array.from(Array(N + 1), () => Array(N + 1).fill(0));
let check = new Array(N + 1).fill(0);
check[1] = 1;
road.sort((a, b) => a[2] - b[2]);
for (let [a, b, c] of road) {
if (!graph[a][b] && !graph[b][a]) {
graph[a][b] = c;
graph[b][a] = c;
}
}
const dfs = (x, target, sum) => {
if (sum > K) return;
if (x === target) {
answer.add(target);
} else {
for (let i = 2; i <= N; i++) {
if (!check[i] && graph[x][i]) {
check[i] = 1;
dfs(i, target, sum + graph[x][i]);
check[i] = 0;
}
}
}
};
let arr = new Array(N).fill(0).map((e, i) => (e = i + 1));
for (let target of arr) {
dfs(1, target, 0);
}
console.log(answer);
return [...answer].length;
};
const solution = (N, road, K) => {
const dis = new Array(N + 1).fill(Infinity);
const graph = Array.from(Array(N + 1), () => []);
for (let [from, to, cost] of road) {
// 무방향 그래프
graph[from].push({ to: to, cost: cost });
graph[to].push({ to: from, cost: cost });
}
const queue = [];
// 첫 노드로 가는 정보를 큐에 삽입하고 bfs를 시작.
queue.push({ to: 1, cost: 0 });
dis[1] = 0;
while (queue.length) {
const { to: cur, cost: cost } = queue.shift();
for (let next of graph[cur]) {
// 다음 좌표의 dis값과 현재 dis값과 다음좌표로가는 코스트
if (dis[next.to] > dis[cur] + next.cost) {
dis[next.to] = dis[cur] + next.cost;
queue.push(next);
}
}
}
return dis.filter((e) => e <= K).length;
};
인접 리스트와 BFS를 활용한 풀이이다.
bfs의 시작과 dis값의 갱신에 대해 설명을 달아두려고 한다.
큐에 들어갈 첫 요소는 1번 노드로 간다는 정보와 그때의 비용이다. 비용은 당연히 0일 것이다.
bfs를 시작. 코드에 cur에 해당하는 값이 1번 노드가 된다.
for of문의 next를 보자. 이 next가 바로 다음 노드라고 생각할 수 있으나 저 next는 {to : 어딘가, cost : 얼마} 이런 식의 정보가 담겨있는 객체이다!!
즉, 다음 노드는 next.to가 된다.
이젠 dis의 갱신이다.
다음 노드의 dis값이 현재 노드의 dis값과 다음 노드로 가는 코스트 크다면! 갱신한다. 작은 값으로 갱신해 나간다.
const input = [
"5 6",
"1",
"5 1 1",
"1 2 2",
"1 3 3",
"2 3 4",
"2 4 5",
"3 4 6",
];
const solution = (input) => {
const [v, e] = input.shift().split(" ").map(Number);
const start = +input.shift();
const edge = input.map((e) => e.split(" ").map(Number));
const graph = Array.from(Array(v + 1), () => []);
const dis = new Array(v + 1).fill(Infinity);
for (const [from, to, cost] of edge) {
graph[from].push({ to: to, cost: cost });
}
dis[start] = 0;
let queue = [{ to: start, cost: 0 }];
while (queue.length) {
const stack = [...queue];
queue = [];
while (stack.length) {
const { to: cur, cost: cost } = stack.pop();
for (const next of graph[cur]) {
if (dis[next.to] > dis[cur] + next.cost) {
dis[next.to] = dis[cur] + next.cost;
queue.push(next);
}
}
}
}
dis.shift();
return dis;
};
console.log(solution(input));
[ 0, 2, 3, 7, Infinity ]