[프로그래머스] Level 3 : 합승 택시 요금(Java)

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/72413

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


💡 풀이

문제를 읽어보면, 도착 지점까지 가기 위한 최단거리를 구해야 하는 것에서 다익스트라를 떠올릴 수 있지만, 어느 지점까지 같이 이동한 후, 도착점 A, B로 이동하게 된다(물론, 아닌 경우도 있지만). 따라서, 한 지점에서 모든 지점까지의 최단거리를 구하는 것을 넘어서(다익스트라), 모든 지점에서 다른 모든 지점까지의 최단 경로를 모두 구해야 한다. 이때, 플로이드-워셜 알고리즘을 사용할 수 있다. 플로이드-워셜에 대한 자세한 내용은 여기서 확인할 수 있다.

 

플로이드-워셜 알고리즘 (Floyd-Warshall) 

모든 지점에서 다른 모든 지점까지의 최단 경로를 모두 구해야 하는 경우

사용할 수 있는 알고리즘이다. 단계마다 거쳐 가는 노드를 기준으로 알고리즘을 수행한다. 시간 복잡도$O(N^3)$ 이 된다.

노드의 개수만큼으로 이루어진 2차원 배열을 선언하는데, 이는 해당 노드 사이의 최단거리가 기록된다. 즉, distance[a][b]에는 a에서 b로 가는 최단거리를 뜻한다. 

 

먼저, distance 배열을 매우 큰 값으로 초기화 한다. 여기서는 최대 요금 금액이 100,000이고 정점의 개수가 200개 이하이기 때문에 불변값(final) MAX_PRICE를 100001 * 200으로 설정했다. 이때, 자신으로 향하면(distance[a][a]와 같은 경우) 0으로 초기화 시킨다. 

static void initDistance(int n) {
    // distance 배열을 INF로 초기화
    // row == col 인 경우, 0으로 초기화
    distance = new int[n+1][n+1];
    for(int y = 1; y < n+1; y++) {
        for(int x = 1; x < n+1; x++) {
            if(y == x) {
                distance[y][x] = 0;
                continue;
            }
            distance[y][x] = MAX_PRICE;
        }
    }
}

 

그리고, 주어진 2차원 배열 fares을 입력 받아, distance 배열을 완성시켜준다. 

static void insertFares(int[][] fares) {
    for(int cand = 0; cand < fares.length; cand++) {
        int node1 = fares[cand][0];
        int node2 = fares[cand][1];
        int price = fares[cand][2];

        distance[node1][node2] = price;
        distance[node2][node1] = price;
    }
}

 

2차원 배열 distance가 완성되었다면, 플로이드-워셜 알고리즘을 수행한다. 

static void floydWarshall(int n) {
    for(int k = 1; k < n + 1; k++) {
        for(int a = 1; a < n + 1; a++) {
            for(int b = 1; b < n + 1; b++) {
                distance[a][b] = Math.min(distance[a][b],
                                         distance[a][k] + distance[k][b]);
            }
        }
    }
}

 

이제, 문제에서 원하는 합동 거리를 구해야 한다.

합동 거리는 모든 노드를 순회하며 탐색한다. 해당 노드(node)에 대해 S부터 node까지의 요금에 node에서 A까지의 요금, node에서 B까지의 요금을 모두 더해주면, S에서 node를 거쳐 A, B로 각각 가는 요금을 계산할 수 있다. 즉, $ (S - node 의 요금) + (node - A 의 요금) + (node - B 의 요금) = (S에서 node를 거쳐 A, B로 가는 요금 = 합동 요금)$이 된다. 이 값들 중 최솟값을 구하면 된다. 

static int getResult(int n, int s, int a, int b){
    int result = MAX_PRICE;

    for(int node = 1; node < n + 1; node++) {
        int newPrice = distance[s][node] + distance[node][a] + distance[node][b];
        result = Math.min(result, newPrice);
    }

    return result;
}

 

전체 코드

전체적인 코드는 다음과 같다. 

class Solution {
    static final int MAX_PRICE = 100001 * 200;
    static int[][] distance;
    
    public int solution(int n, int s, int a, int b, int[][] fares) {
        initDistance(n);
        insertFares(fares);
        floydWarshall(n);
        
        return getResult(n, s, a, b);
    }
    
    static void initDistance(int n) {
        // distance 배열을 INF로 초기화
        // row == col 인 경우, 0으로 초기화
        distance = new int[n+1][n+1];
        for(int y = 1; y < n+1; y++) {
            for(int x = 1; x < n+1; x++) {
                if(y == x) {
                    distance[y][x] = 0;
                    continue;
                }
                distance[y][x] = MAX_PRICE;
            }
        }
    }
    
    static void insertFares(int[][] fares) {
        for(int cand = 0; cand < fares.length; cand++) {
            int node1 = fares[cand][0];
            int node2 = fares[cand][1];
            int price = fares[cand][2];

            distance[node1][node2] = price;
            distance[node2][node1] = price;
        }
    }
    
    static void floydWarshall(int n) {
        for(int k = 1; k < n + 1; k++) {
            for(int a = 1; a < n + 1; a++) {
                for(int b = 1; b < n + 1; b++) {
                    distance[a][b] = Math.min(distance[a][b],
                                             distance[a][k] + distance[k][b]);
                }
            }
        }
    }
    
    static int getResult(int n, int s, int a, int b){
        int result = MAX_PRICE;
        
        for(int node = 1; node < n + 1; node++) {
            int newPrice = distance[s][node] + distance[node][a] + distance[node][b];
            result = Math.min(result, newPrice);
        }
        
        return result;
    }
}