[프로그래머스 Level 2] 배달
1분 읽기
풀이 1: 다익스트라 - 배열
function solution(N, road, K) {
const map = Array.from({ length: N }, () => new Array(N).fill(Infinity));
road.forEach(([v1, v2, takes]) => {
v1-- && v2--;
map[v1][v2] = map[v2][v1] = Math.min(map[v1][v2], takes);
});
function dijkstra(source){
const dist = [...map[source]]; // ✅ 우선순위 큐로 개선 가능
const visited = new Array(N).fill(false);
// O(N)
function getSmallIdx(){
let min = Infinity;
let idx = 0;
// 1 ≤ N ≤ 50
dist.forEach((v, i) => {
if(v < min && !visited[i]){
min = v;
idx = i;
}
});
return idx;
}
dist[source] = 0;
visited[source] = true;
// O(N^2) → (N-2) * (N + N)
for(let i = 0; i < N - 2; i++){
const current = getSmallIdx();
visited[current] = true;
for(let j = 0; j < N; j++){
if(visited[j]) continue;
if(map[current][j] === Infinity) continue;
dist[j] = Math.min(dist[j], dist[current] + map[current][j]);
}
}
return dist;
}
return dijkstra(0).filter(v => v <= K).length;
}Shortest Path2편 중 2번째
- 1. [2021 KAKAO BLIND RECRUITMENT Level 3] 합승 택시 요금
- 2. [프로그래머스 Level 2] 배달
관련 글
4분 읽기
소수 구하기
소수 판별법과 소수를 구하는 알고리즘을 정리합니다.
1분 읽기
[프로그래머스 Level 2] 미로 탈출
프로그래머스 미로 탈출을 BFS로 풀이합니다.
1분 읽기
[프로그래머스 Level 2] 마법의 엘리베이터
프로그래머스 마법의 엘리베이터를 자리수 그리디로 풀이합니다.