ALGORITHM/PROGRAMMERS
[프로그래머스] 합승 택시 요금 (2021 KAKAO BLIND RECRUITMENT)
0298
2021. 1. 31. 21:48
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
2021-01-31
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
53
54
55
56
57
|
public class Solution72413 {
public static int arr[][], dist[][];
public static int solution(int n, int s, int a, int b, int[][] fares) {
int answer = 987654321;
arr = new int[n+1][n+1];
dist = new int[n+1][n+1];
for(int i = 0; i < fares.length; i++) {
arr[fares[i][0]][fares[i][1]] = fares[i][2];
arr[fares[i][1]][fares[i][0]] = fares[i][2];
}
//초기화
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
dist[i][j] = (arr[i][j] == 0 && (i!=j)) ? 987654321 : arr[i][j];
}
}
for(int k = 1; k <= n; k++) { // 거쳐가는 노드
for(int i = 1; i <= n; i++) { // 출발 노드
for(int j = 1; j <= n; j++) { // 도착 노드
if(dist[i][j] > dist[i][k] + dist[k][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
for(int i = 1; i <= n; i++) {
if(dist[s][i] != 987654321) {
answer = Math.min(answer, (dist[s][i] + dist[i][a] + dist[i][b]));
}
}
return answer;
}
public static void main(String[] args) {
int n = 6;
int s = 4;
int a = 6;
int b = 2;
int fares[][] = {
{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}
};
System.out.println(solution(n, s, a, b, fares));
}
}
|
cs |
#문제풀이
처음에는 다익스트라 알고리즘으로 풀어보려고 했었다. 생각한 로직이 잘못 됐는지 채점이 반토막이 나서,
그냥 플로이드 와샬로 풀었다.
1. arr 배열에 각 지점별 택시요금을 저장하고, 그것을 이용하여 dist 배열을 초기화 했다.
2. 그리고 dist배열을 플로이드와샬 알고리즘으로 계산 하였다.
3. 마지막에 모든 노드를 기준으로 dist[출발점][노드] + dist[노드][a] + dist[노드][b]를 계산하여 가장 작은 값을 답으로 출력하였다.