문제 출처: https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV18P2B6Iu8CFAZN&categoryId=AV18P2B6Iu8CFAZN&categoryType=CODE&problemTitle=1263&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
for (int t = 0; t < T; t++) {
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int N = Integer.parseInt(tokenizer.nextToken());
int[][] adjMatrix = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
adjMatrix[i][j] = Integer.parseInt(tokenizer.nextToken());
if (i != j && adjMatrix[i][j] == 0) adjMatrix[i][j] = 2000;
}
}
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
adjMatrix[i][j] = Math.min(adjMatrix[i][j], adjMatrix[i][k] + adjMatrix[k][j]);
}
}
}
int ans = 2000;
for (int i = 0; i < N; i++) {
int temp = 0;
for (int j = 0; j < N; j++) {
temp += adjMatrix[i][j];
}
if (ans > temp) ans = temp;
}
sb.append("#").append(t + 1).append(" ");
sb.append(ans).append("\n");
}
System.out.println(sb);
}
}
- 모든 정점들 간의 거리를 구해야하므로 플로이드 워셜 알고리즘을 적용하여 풀었다.