11404번: 플로이드
첫째 줄에 도시의 개수 n이 주어지고 둘째 줄에는 버스의 개수 m이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스의 출발 도시의 번호가
www.acmicpc.net
package 백준.자바.플로이드_11404;
import java.io.*;
import java.util.*;
public class Main {
public void solution() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int M = Integer.parseInt(br.readLine());
int[][] floyd = new int[N+1][N+1];
for(int i = 0; i < N+1; i++){
Arrays.fill(floyd[i], 100_000_000);
floyd[i][i] = 0;
}
for(int i = 0; i < M; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
floyd[a][b] = Math.min(floyd[a][b], c);
}
// k, a, b = 1 to n+1
for(int k = 1; k < N+1; k++){
for(int a = 1; a < N+1; a++){
for(int b = 1; b < N+1; b++){
floyd[a][b] = Math.min(floyd[a][b], floyd[a][k] + floyd[k][b]);
}
}
}
StringBuilder sb = new StringBuilder();
for(int i = 1; i < N+1; i++){
for(int j = 1; j < N+1; j++){
if(floyd[i][j] == 100_000_000) sb.append("0 ");
else sb.append(floyd[i][j] + " ");
}
sb.append('\n');
}
System.out.print(sb);
}
public static void main(String[] args) throws Exception{
new Main().solution();
}
}
'문제풀이 > 백준' 카테고리의 다른 글
[Java] 감시 15683 (0) | 2024.08.22 |
---|---|
보물섬 2589 (0) | 2024.04.11 |
최단경로 1753 (0) | 2024.04.09 |
국영수 10825 (0) | 2024.04.08 |
둘만의 암호 Java (0) | 2024.02.25 |