You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
다익스트라 알고리즘의 시간 복잡도 개선을 고려해볼 수 있습니다. 현재 구현은 O(E log V)이지만, 더 효율적인 우선순위 큐 구현이나 희소 그래프 최적화 기법을 적용할 수 있습니다.
functionsolution(n,s,a,b,fares){// 0. 다익스트라에 필요한 데이터 준비하기// adj: 인접 리스트 (원소: [v, w])constadj=Array.from({length: n+1},()=>[]);for(const[c,d,f]offares){adj[c].push([d,f]);adj[d].push([c,f]);}// 1. 다익스트라 구현// start: 경로를 계산할 시작 지점.// 시작 지점부터 다른 전체 노드까지의 각 최단 경로를 반환한다.functiondijkstra(start){// 0) 초기 설정constdist=newArray(n+1).fill(Infinity);dist[start]=0;constminHeap=newHeap(([c1,v1],[c2,v2])=>c1<c2);minHeap.push([0,start]);// 1) minHeap이 빌 때까지 반복한다.while(minHeap.size()>0){const[cost,u]=minHeap.pop();// NOTE : dist 정보와 cost 정보가 다르다면 구버전 정보이므로 넘어간다. (이미 처리한 노드임을 의미)if(cost!==dist[u])continue;// 2) u의 간선들을 모두 탐색한다.for(const[v,w]ofadj[u]){// 3) v로 가는데 걸리는 비용의 최솟값을 업데이트한다.constnextCost=cost+w;if(nextCost<dist[v]){dist[v]=nextCost;minHeap.push([nextCost,v]);}}}returndist;}// 2. S에서 출발하는 경로의 촤단거리constdistS=dijkstra(s);// 3. A에서 출발하는 경로의 최단거리 (중간지점 - A까지의 거리 계산용)constdistA=dijkstra(a);// 4. B에서 출발하는 경로의 최단거리 (중간지점 - B까지의 거리 계산용)constdistB=dijkstra(b);// 5. 모든 중간지점 c를 확인하면서 총 비용이 최소가 되는 c를 찾는다.// 합승을 안해도 되기 때문에 시작지점도 확인한다.letanswer=Infinity;for(letc=1;c<=n;c++){answer=Math.min(answer,distS[c]+distA[c]+distB[c]);}returnanswer;}
functionsolution(n,s,a,b,fares){// 0. 다익스트라에 필요한 데이터 준비하기// adj: 인접 리스트 (원소: [v, w])constadj=Array.from({length: n+1},()=>[]);for(const[c,d,f]offares){adj[c].push([d,f]);adj[d].push([c,f]);}// 1. 다익스트라 구현// start: 경로를 계산할 시작 지점.// 시작 지점부터 다른 전체 노드까지의 각 최단 경로를 반환한다.functiondijkstra(start){// 0) 초기 설정constdist=newArray(n+1).fill(Infinity);dist[start]=0;constminHeap=newHeap(([c1,v1],[c2,v2])=>c1<c2);minHeap.push([0,start]);// 1) minHeap이 빌 때까지 반복한다.while(minHeap.size()>0){const[cost,u]=minHeap.pop();// NOTE : dist 정보와 cost 정보가 다르다면 구버전 정보이므로 넘어간다. (이미 처리한 노드임을 의미)if(cost!==dist[u])continue;// 2) u의 간선들을 모두 탐색한다.for(const[v,w]ofadj[u]){// 3) v로 가는데 걸리는 비용의 최솟값을 업데이트한다.constnextCost=cost+w;if(nextCost<dist[v]){dist[v]=nextCost;minHeap.push([nextCost,v]);}}}returndist;}// 2. S에서 출발하는 경로의 촤단거리constdistS=dijkstra(s);// 3. A에서 출발하는 경로의 최단거리 (중간지점 - A까지의 거리 계산용)constdistA=dijkstra(a);// 4. B에서 출발하는 경로의 최단거리 (중간지점 - B까지의 거리 계산용)constdistB=dijkstra(b);// 5. 모든 중간지점 c를 확인하면서 총 비용이 최소가 되는 c를 찾는다.// 합승을 안해도 되기 때문에 시작지점도 확인한다.letanswer=Infinity;for(letc=1;c<=n;c++){answer=Math.min(answer,distS[c]+distA[c]+distB[c]);}returnanswer;}
-function dijkstra(start) {+function dijkstra(start, n, adj) {
const dist = new Array(n + 1).fill(Infinity);
dist[start] = 0;
const minHeap = new Heap(([c1, v1], [c2, v2]) => c1 < c2);
minHeap.push([0, start]);
while (minHeap.size() > 0) {
const [cost, u] = minHeap.pop();
if (cost !== dist[u]) continue;
for (const [v, w] of adj[u]) {
const nextCost = cost + w;
if (nextCost < dist[v]) {
dist[v] = nextCost;
minHeap.push([nextCost, v]);
}
}
}
return dist;
}
+function solution(n, s, a, b, fares) {+ const adj = createAdjacencyList(n, fares);+ const distS = dijkstra(s, n, adj);+ const distA = dijkstra(a, n, adj);+ const distB = dijkstra(b, n, adj);+ ...+}+
Suggestion importance[1-10]: 8
__
Why: Modifying the dijkstra function to accept n and adj as parameters increases function independence and reusability. This makes the function more flexible and easier to test.
Medium
인접 리스트 생성 로직 분리
다익스트라 알고리즘을 위한 인접 리스트 생성 로직을 별도의 함수로 분리하면 코드의 가독성과 모듈성을 높일 수 있습니다. 이렇게 하면 데이터 준비 로직을 더 명확하게 분리할 수 있습니다.
-function solution(n, s, a, b, fares) {- // 0. 다익스트라에 필요한 데이터 준비하기- // adj: 인접 리스트 (원소: [v, w])+function createAdjacencyList(n, fares) {
const adj = Array.from({ length: n + 1 }, () => []);
for (const [c, d, f] of fares) {
adj[c].push([d, f]);
adj[d].push([c, f]);
}
+ return adj;+}++function solution(n, s, a, b, fares) {+ const adj = createAdjacencyList(n, fares);
...
}
Suggestion importance[1-10]: 7
__
Why: Extracting the adjacency list creation into a separate function improves code modularity and readability. The suggestion provides a clean separation of concerns without changing the core logic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
User description
오늘도 멋져요 👍✨
PR Type
Enhancement
Description
프로그래머스 Level 3 문제 '합승 택시 요금' 해결
다익스트라 알고리즘을 사용한 최단 경로 계산
최소 택시 요금 찾는 솔루션 구현