CS/알고리즘_KAKAO BLIND RECRUITMENT

2021 KAKAO BLIND RECRUITMENT : 합승 택시 요금(플로이드 워셜)

Jedy_Kim 2021. 10. 20. 20:21
728x90

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

 

코딩테스트 연습 - 합승 택시 요금

6 4 6 2 [[4, 1, 10], [3, 5, 24], [5, 6, 2], [3, 1, 41], [5, 1, 24], [4, 6, 50], [2, 4, 66], [2, 3, 22], [1, 6, 25]] 82 7 3 4 1 [[5, 7, 9], [4, 6, 4], [3, 6, 1], [3, 2, 3], [2, 1, 6]] 14 6 4 5 6 [[2,6,6], [6,3,7], [4,6,7], [6,5,11], [2,5,12], [5,3,20], [2,4

programmers.co.kr

 

// 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
 
class Solution {
    
    static final int INF = 40000000;
    int[][] Dist = new int[200][200];
    
    void floyd(int n) {
        for(int k = 0; k < n; ++k) { // 경유지
            for(int i = 0; i < n; ++i) { // 시작점
                for(int j = 0; j < n; ++j) { // 도착점
                    if(Dist[i][k] + Dist[k][j] < Dist[i][j]) {
                        Dist[i][j] = Dist[i][k] + Dist[k][j];
                    }
                }
            }
        }
    }
    
    public int solution(int n, int s, int a, int b, int[][] fares) {
        
        // 초기화
        for(int i=0; i<n; ++i) {
            for(int j=0; j<n; ++j) {
                // 출발점과 도착점이 같으면 : 0
                if(i == j) Dist[i][j] = 0;
                else Dist[i][j] = INF;                
            }
        }
        
        // 그래프 방향성 : X
        for(int[] edge : fares) {            
            // [시작점][도착점] = 비용
            Dist[edge[0]-1][edge[1]-1= edge[2];    
            // [도착점][시작점] = 비용
            Dist[edge[1]-1][edge[0]-1= edge[2];
        }
        
        // 플로이드 와샬
        floyd(n);
        
        --s;
        --a;
        --b;
                
        int answer = INF;
        for(int k=0; k<n; ++k) {
            answer = Math.min(answer, (Dist[s][k] + Dist[k][a] + Dist[k][b]));
        }
        return answer;
    }
}
cs

 

반응형