Cod sursa(job #1495687)

Utilizator BFlorin93Balint Florin-Lorand BFlorin93 Data 3 octombrie 2015 13:45:32
Problema Floyd-Warshall/Roy-Floyd Scor 10
Compilator java Status done
Runda Arhiva educationala Marime 1.74 kb
import java.io.*;
import java.util.Scanner;

/**
 * Created by bflorin on 03.10.2015.
 */
public class Main {
    private static final String INPUT_FILE_NAME = "royfloyd.in";
    private static final String OUTPUT_FILE_NAME  = "royfloyd.out";
    private static int[][] matrixCost;
    private static int n;

    public static void main(String[] args){
        try(Scanner reader = new Scanner(new FileReader(INPUT_FILE_NAME))
        ) {

            n = reader.nextInt();
            matrixCost = new int[n][n];

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    matrixCost[i][j] = reader.nextInt();
                }
            }

            floydWarshall(matrixCost, n);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try(PrintWriter writer = new PrintWriter(new FileWriter(OUTPUT_FILE_NAME))){
            for(int i = 0; i < n; i++){
                for(int j = 0; j < n; j++){
                    if(matrixCost[i][j] < Integer.MAX_VALUE) {
                        writer.print(matrixCost[i][j]);
                    }
                    else writer.print(0);

                    writer.print(' ');
                }
                writer.print('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void floydWarshall(int[][] matrixCost, int n) {
        for(int k = 0; k < n; k++){
            for(int i = 0; i < n; i++){
                for(int j = 0; j < n; j++){
                    if(matrixCost[i][k] + matrixCost[k][j] < matrixCost[i][j]){
                        matrixCost[i][j] = matrixCost[i][k] + matrixCost[k][j];
                    }
                }
            }
        }
    }

}