본문으로 바로가기

[BaekJoon] 백준 11404번: 플로이드

category 알고리즘/백준 2022. 9. 6. 11:40

https://www.acmicpc.net/problem/11404

 

11404번: 플로이드

첫째 줄에 도시의 개수 n이 주어지고 둘째 줄에는 버스의 개수 m이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스의 출발 도시의 번호가

www.acmicpc.net

 

 

플로이드 와샬 알고리즘을 구현하는 문제이다. 

 

전체 코드 > 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    static int[][] city;
    static int M;
    static int N;
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        N = Integer.parseInt(br.readLine());
        M = Integer.parseInt(br.readLine());
    
        city = new int[N+1][N+1];
        
        for(int i = 1; i<=N; i++) {
            for(int j = 1; j<=N; j++) {
                if (i == j) {
                    city[i][j] = 0;
                } else {
                    city[i][j] = 99999999;
                }
            }
        }
        
        for(int i = 0; i<M; i++) {
            String[] input = br.readLine().split(" ");
            int a = Integer.parseInt(input[0]);
            int b = Integer.parseInt(input[1]);
            int c = Integer.parseInt(input[2]);
            
            city[a][b] = Math.min(city[a][b], c);
        }
        
        for(int i = 1; i<=N; i++) {
            for(int j = 1; j<=N; j++) {
                for(int k = 1; k<=N; k++) {
                    if (j != k) {
                        city[j][k] = Math.min(city[j][i] + city[i][k], city[j][k]);
                    }
                }
            }
        }
        
        for(int i = 1; i<=N; i++) {
            for(int j = 1; j<=N; j++) {
                if (city[i][j] >= 99999999) {
                    System.out.print("0");
                } else {
                    System.out.print(city[i][j]);
                }
                
                if (j != N) {
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
        
    }
}