Skip to content

2026-02-08 문제 풀었어요#29

Merged
uyeon0 merged 1 commit intomainfrom
upload
Feb 8, 2026
Merged

2026-02-08 문제 풀었어요#29
uyeon0 merged 1 commit intomainfrom
upload

Conversation

@uyeon0
Copy link
Collaborator

@uyeon0 uyeon0 commented Feb 8, 2026

User description

오늘도 멋져요 👍✨


PR Type

Enhancement


Description

  • 프로그래머스 Level 3 문제 '합승 택시 요금' 해결

  • 다익스트라 알고리즘을 사용한 최단 경로 계산

  • 최소 택시 요금 찾는 솔루션 구현


@uyeon0 uyeon0 added the programmers Programmers 문제 풀이 label Feb 8, 2026
@github-actions
Copy link

github-actions bot commented Feb 8, 2026

PR Reviewer Guide 🔍

🧪 No relevant tests
⚡ Recommended focus areas for review

성능 최적화

다익스트라 알고리즘의 시간 복잡도 개선을 고려해볼 수 있습니다. 현재 구현은 O(E log V)이지만, 더 효율적인 우선순위 큐 구현이나 희소 그래프 최적화 기법을 적용할 수 있습니다.

function solution(n, s, a, b, fares) {
  // 0. 다익스트라에 필요한 데이터 준비하기
  // adj: 인접 리스트 (원소: [v, w])
  const adj = Array.from({ length: n + 1 }, () => []);
  for (const [c, d, f] of fares) {
    adj[c].push([d, f]);
    adj[d].push([c, f]);
  }

  // 1. 다익스트라 구현
  // start: 경로를 계산할 시작 지점.
  // 시작 지점부터 다른 전체 노드까지의 각 최단 경로를 반환한다.
  function dijkstra(start) {
    // 0) 초기 설정
    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]);

    // 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] of adj[u]) {
        // 3) v로 가는데 걸리는 비용의 최솟값을 업데이트한다.
        const nextCost = cost + w;
        if (nextCost < dist[v]) {
          dist[v] = nextCost;
          minHeap.push([nextCost, v]);
        }
      }
    }

    return dist;
  }

  // 2. S에서 출발하는 경로의 촤단거리
  const distS = dijkstra(s);
  // 3. A에서 출발하는 경로의 최단거리 (중간지점 - A까지의 거리 계산용)
  const distA = dijkstra(a);
  // 4. B에서 출발하는 경로의 최단거리 (중간지점 - B까지의 거리 계산용)
  const distB = dijkstra(b);

  // 5. 모든 중간지점 c를 확인하면서 총 비용이 최소가 되는 c를 찾는다.
  // 합승을 안해도 되기 때문에 시작지점도 확인한다.
  let answer = Infinity;
  for (let c = 1; c <= n; c++) {
    answer = Math.min(answer, distS[c] + distA[c] + distB[c]);
  }
  return answer;
}
엣지 케이스

다음 엣지 케이스를 고려해야 합니다:

  1. 노드 간 연결이 없는 경우
  2. 시작점과 도착점이 동일한 경우의 최단 경로 계산
function solution(n, s, a, b, fares) {
  // 0. 다익스트라에 필요한 데이터 준비하기
  // adj: 인접 리스트 (원소: [v, w])
  const adj = Array.from({ length: n + 1 }, () => []);
  for (const [c, d, f] of fares) {
    adj[c].push([d, f]);
    adj[d].push([c, f]);
  }

  // 1. 다익스트라 구현
  // start: 경로를 계산할 시작 지점.
  // 시작 지점부터 다른 전체 노드까지의 각 최단 경로를 반환한다.
  function dijkstra(start) {
    // 0) 초기 설정
    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]);

    // 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] of adj[u]) {
        // 3) v로 가는데 걸리는 비용의 최솟값을 업데이트한다.
        const nextCost = cost + w;
        if (nextCost < dist[v]) {
          dist[v] = nextCost;
          minHeap.push([nextCost, v]);
        }
      }
    }

    return dist;
  }

  // 2. S에서 출발하는 경로의 촤단거리
  const distS = dijkstra(s);
  // 3. A에서 출발하는 경로의 최단거리 (중간지점 - A까지의 거리 계산용)
  const distA = dijkstra(a);
  // 4. B에서 출발하는 경로의 최단거리 (중간지점 - B까지의 거리 계산용)
  const distB = dijkstra(b);

  // 5. 모든 중간지점 c를 확인하면서 총 비용이 최소가 되는 c를 찾는다.
  // 합승을 안해도 되기 때문에 시작지점도 확인한다.
  let answer = Infinity;
  for (let c = 1; c <= n; c++) {
    answer = Math.min(answer, distS[c] + distA[c] + distB[c]);
  }
  return answer;
}

@github-actions
Copy link

github-actions bot commented Feb 8, 2026

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
다익스트라 함수 매개변수 개선

다익스트라 함수에서 외부 변수 nadj에 의존하는 대신, 이를 매개변수로 전달하면 함수의 독립성과 재사용성을 높일 수 있습니다. 이는 함수의
순수성을 개선하고 테스트 용이성을 높입니다.

Programmers/Level3/72413_합승_택시_요금.js [101-125]

-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
인접 리스트 생성 로직 분리

다익스트라 알고리즘을 위한 인접 리스트 생성 로직을 별도의 함수로 분리하면 코드의 가독성과 모듈성을 높일 수 있습니다. 이렇게 하면 데이터 준비 로직을
더 명확하게 분리할 수 있습니다.

Programmers/Level3/72413_합승_택시_요금.js [89-96]

-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.

Medium

@yoouyeon yoouyeon self-assigned this Feb 8, 2026
@yoouyeon yoouyeon added the ready-to-merge pr을 머지해주세요 label Feb 8, 2026
@uyeon0 uyeon0 merged commit 105fd0c into main Feb 8, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

programmers Programmers 문제 풀이 ready-to-merge pr을 머지해주세요

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants