๐ ๋ฌธ์ ๋งํฌ
https://school.programmers.co.kr/learn/courses/30/lessons/72413
๐ฎ ๋ฌธ์ ํด๊ฒฐ ๋ฐฉ๋ฒ
์ต๋จ ๊ฑฐ๋ฆฌ ์๊ณ ๋ฆฌ์ฆ์ ์ ์ฉํ๋ ๊ฒ์ด ๋ฌธ์ ์ ํคํฌ์ธํธ์ด๋ค.
๋ชจ๋ ๋์๋ก๋ถํฐ ์ถ๋ฐํด ๋ชจ๋ ๋์๋ก ๋์ฐฉํ๋ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํด์ค๋ค. ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋ ๋ฐฉ์์ ํฌ๊ฒ ๋๊ฐ์ง๊ฐ ์๋ค. (๋ฌด๋ฐฉํฅ ์์ ๊ทธ๋ํ ๊ธฐ์ค)
- ํ๋์ ์ ์ ๊ธฐ์ค ์ต๋จ ๊ฑฐ๋ฆฌ๊ตฌํ๊ธฐ → ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ : ๋ชจ๋ ๋์์ ๋ํด ๊ตฌํด์ผํ๋ฏ๋ก for๋ฌธ์ ํตํด ๋ชจ๋ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋ค.
- ๋ชจ๋ ์ ์ ๊ธฐ์ค ์ต๋จ ๊ฑฐ๋ฆฌ ๊ตฌํ๊ธฐ → ํ๋ก์ด๋ ์์ ์๊ณ ๋ฆฌ์ฆ
๋ชจ๋ ์ ์ ์ ๋ํ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋ ์๊ณ ๋ฆฌ์ฆ์ ํ๋ก์ด๋ ์์ ์ ์ผ๋ฐ์ ์ผ๋ก ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ํ๋ก์ด๋ ์์ ์๊ณ ๋ฆฌ์ฆ์ ํตํด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ค.
(๋ค์ต์คํธ๋ผ ์ด์ฉ์ ์๊ฐ์ด๊ณผ ๋๋ ๊ฒ ํ์ธ!)
- ๋ชจ๋ ๋์ฐฉ ๋์์ ๋ํ ์ต์์๊ธ์ ๊ตฌํ๊ธฐ ์ํ fees ๋ฐฐ์ด ์ ์ธ ๋ฐ ๋๋ก ์ด๊ธฐํ
- ํ๋ก์ด๋ ์์ ์๊ณ ๋ฆฌ์ฆ ์คํ
- ์ถ๋ฐ ๋์์ธ S์์ ๊ฐ๊ฐ A, B์ ๋๋ฌํ ์ ์๋ ์ต์ด์ ์ต์์๊ธ์ ํฉ์น์ํ๊ณ ๊ฐ๊ฐ ๊ฐ ๊ฒฝ์ฐ →
fees[s][a] + fees[s][b];
- ์ถ๋ฐ ๋์์ธ S์์ ํฉ์นํด ๊ฐ๊ฐ์ ๋์๋ก ๊ฐ ํ ํด๋น ๋์์์ ๋ด๋ ค์ ๋ฐ๋ก ํ์ํ๊ณ ๊ฐ ๊ฒฝ์ฐ →
fees[s][city] + fees[city][a] + fees[city][b];
- 3, 4์ค ์ต์ ์๊ธ์๊ตฌํด ๋ฆฌํด
๐ฉ Java ์ฝ๋
package com.second.algorithm.programmers;
import java.util.Arrays;
public class Solution_72413_ํฉ์น_ํ์_์๊ธ {
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}};
int rst = solution(n, s, a, b, fares);
System.out.println("rst = " + rst);
}
private static final int INF = 200 * 100_000;
private static int solution(int n, int s, int a, int b, int[][] fares) {
// ์๊ธ ๋ฐฐ์ด ์ด๊ธฐํ
int[][] fees = new int[n + 1][n + 1];
for (int city = 1; city <= n; city++) {
Arrays.fill(fees[city], INF);
fees[city][city] = 0;
}
// ๋๋ก ์์ฑ
initFees(n, fares, fees);
// ํ๋ก์ด๋ ์์
์๊ณ ๋ฆฌ์ฆ
floydWarshall(n, fees);
// ์ต์ ์๊ธ ๊ตฌํ๊ธฐ
int minFee = fees[s][a] + fees[s][b]; // ์ต์ด ํฉ์น ์ํ ๊ฒฝ์ฐ๊ฐ ์ต์
// ํฉ์นํ ๊ฒฝ์ฐ s์์ ์ถ๋ฐํด ๋์ฐฉํ ์ ์๋ ๋์์์ ๋ค์ ๊ฐ๊ฐ์ ๋์๋ก์ ์ต์์๊ธ ๊ตฌํ ๊ฐ๊ณผ ๋น๊ต
for (int city = 1; city <= n; city++) {
minFee = Math.min(minFee, fees[s][city] + fees[city][a] + fees[city][b]);
}
return minFee;
}
private static void floydWarshall(int n, int[][] fees) {
for (int mid = 1; mid <= n; mid++) {
for (int start = 1; start <= n; start++) {
for (int end = 1; end <= n; end++) {
if (start == end) continue;
if (fees[start][end] > fees[start][mid] + fees[mid][end]) {
fees[start][end] = fees[start][mid] + fees[mid][end];
}
}
}
}
}
private static void initFees(int n, int[][] fares, int[][] fees) {
for (int[] fare : fares) {
int departure = fare[0];
int destination = fare[1];
int fee = fare[2];
fees[departure][destination] = fee;
fees[destination][departure] = fee;
}
}
}
๋ฐ์ํ
'Algorithm > ๊ทธ๋ํ(Graph)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค, Java] 2623๋ฒ : ์์ ํ๋ก๊ทธ๋จ (0) | 2022.08.09 |
---|---|
[๋ฐฑ์ค, Java] 1414๋ฒ : ๋ถ์ฐ์ด์๋๊ธฐ (0) | 2022.06.08 |
[๋ฐฑ์ค, Java] 18352๋ฒ : ํน์ ๊ฑฐ๋ฆฌ์ ๋์ ์ฐพ๊ธฐ (0) | 2022.05.13 |
[๋ฐฑ์ค, Java] 1707๋ฒ : ์ด๋ถ ๊ทธ๋ํ (0) | 2022.04.27 |