문제풀이/ShortestPath

[PS] BOJ11404 플로이드 ( Floyd-Warshall ) with JAVA

IT록흐 2023. 9. 14. 06:26
반응형

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

 

11404번: 플로이드

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

www.acmicpc.net

 

 

◎ 문제풀이 

 

가장 기본적인 플로이드-워셜 알고리즘 문제이다. 

 

 

[Algorithm] 플로이드-워셜(Floyd-Warshall) 알고리즘이란?

[Algorithm] 다익스트라 알고리즘(Dijkstra)이란? 다익스트라 알고리즘(Dijkstra) 다익스트라 알고리즘은 특정지점에서 다른지점으로 가는 최단경로를 구하는 알고리즘이다. 다익스트라 알고리즘은 그

lordofkangs.tistory.com

 

알고리즘은 위 포스팅을 참고하면 된다. 

 

◎ 코드


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

import static java.lang.Math.*;

//BOJ11404 플로이드
public class Main {

    static int n,m;
    static final int INF = Integer.MAX_VALUE;
    static int[][] floyd;


    public static void main(String[] args) throws IOException {
        init();
        solution();
        print();

    }

    private static void solution() {
        for(int mid=1;mid<=n;mid++){
            for(int start=1;start<=n;start++){
                for(int end=1;end<=n;end++){
                    if(floyd[start][mid] == INF || floyd[mid][end] == INF) continue;
                    int cost = floyd[start][mid] + floyd[mid][end];
                    floyd[start][end] = min(floyd[start][end],cost);
                }
            }
        }
    }

    private static void init() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = Integer.parseInt(br.readLine());
        m = Integer.parseInt(br.readLine());

        floyd = new int[n+1][n+1];

        for(int i=0;i<n+1;i++){
            for(int j=0;j<n+1;j++){
                if(i==j) floyd[i][j] = 0;
                else floyd[i][j] = INF;
            }
        }

        for(int i=0;i<m;i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int start = Integer.parseInt(st.nextToken());
            int des = Integer.parseInt(st.nextToken());
            int cost = Integer.parseInt(st.nextToken());

            floyd[start][des] = min(floyd[start][des],cost);

        }
    }

    private static void print() {
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(floyd[i][j] != INF) System.out.print(floyd[i][j]+" ");
                else System.out.print(0 + " ");
            }
            System.out.println();
        }
    }
}
반응형