Cod sursa(job #1495683)

Utilizator BFlorin93Balint Florin-Lorand BFlorin93 Data 3 octombrie 2015 13:39:01
Problema Floyd-Warshall/Roy-Floyd Scor 10
Compilator java Status done
Runda Arhiva educationala Marime 2.17 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){
        int[][] pathMatrix = new int[0][];
        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();
                }
            }

            pathMatrix = new int[n][n];
            floydWarshall(matrixCost, pathMatrix, 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(pathMatrix[i][j] < Integer.MAX_VALUE) {
                        writer.print(pathMatrix[i][j]);
                    }
                    else writer.print(0);

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

    }

    private static void floydWarshall(int[][] matrixCost, int[][] pathMatrix, int n) {
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                pathMatrix[i][j] = Integer.MAX_VALUE;
            }
        }

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

        for(int k = 0;k < n; k++){
            for(int i = 0; i < n; i++){
                for(int j = 0; j < n; j++){
                    if(pathMatrix[i][k] + pathMatrix[k][j] < pathMatrix[i][j]){
                        pathMatrix[i][j] = pathMatrix[i][k] + pathMatrix[k][j];
                    }
                }
            }
        }
    }

}