import java.io.*;
import java.util.Scanner;


public class floyd {
    private static int[][] adjMatrix;
    private static int[][] pMatrix;
    private static final String OUTPUT_FILE = "output.txt";

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.err.println("Usage: java Floyd <graph-file>");
            return;
        }

        try (Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0])))) {
            createFile();

            int problemCount = 0;

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();

                if (line.startsWith("Problem")) {
                    problemCount++;
                    int n = extractNumberOfVertices(line);

                    if (n < 5 || n > 10) {
                        throw new IllegalArgumentException("Invalid number of vertices.");
                    }

                    // Read adjacency matrix for the current problem
                    initializeMatrices(n, scanner);

                    // Compute shortest paths and print results
                    calculateShortestPaths();
                    printResult(problemCount, n);
                }
            }
        }
    }

    private static void createFile() throws FileNotFoundException {
        PrintWriter writer = new PrintWriter(OUTPUT_FILE);
        writer.close();
    }

    private static int extractNumberOfVertices(String line) {
        // Extracts the number of vertices from the line
        String[] parts = line.split("n = ");
        return Integer.parseInt(parts[1].trim());
    }

    private static void initializeMatrices(int n, Scanner scanner) {
        adjMatrix = new int[n][n];
        pMatrix = new int[n][n];
    
        // Initialize matrices
        for (int i = 0; i < n; i++) {
            String[] values = scanner.nextLine().trim().split("\\s+");
            for (int j = 0; j < n; j++) {
                if (values[j].equals("INF")) {
                    adjMatrix[i][j] = Integer.MAX_VALUE;
                } else {
                    int weight = Integer.parseInt(values[j]);
                    adjMatrix[i][j] = weight;
                }
    
                // Set pMatrix[i][j] according to whether there is a direct path from i to j
                if (adjMatrix[i][j] != Integer.MAX_VALUE && i != j) {
                    pMatrix[i][j] = j; // Direct path from i to j, so set pMatrix[i][j] to j
                } else {
                    pMatrix[i][j] = -1; // No direct path from i to j
                }
            }
        }
    }
    
    private static void calculateShortestPaths() {
        int n = adjMatrix.length;
    
        // Floyd-Warshall algorithm
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (adjMatrix[i][k] != Integer.MAX_VALUE && adjMatrix[k][j] != Integer.MAX_VALUE) {
                        long newDistance = (long) adjMatrix[i][k] + adjMatrix[k][j];
                        if (newDistance < adjMatrix[i][j]) {
                            adjMatrix[i][j] = (int) newDistance;
                            pMatrix[i][j] = pMatrix[i][k]; // Update pMatrix to reflect path from i to j via k
                        }
                    }
                }
            }
        }
    }
    
    private static void printResult(int problemCount, int n) throws FileNotFoundException, IOException {
        try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE, true)))) {
            out.println("Problem" + problemCount + ": n = " + n);
            out.println("Pmatrix:");
    
            // Output the pMatrix for the problem
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == j) {
                        out.print("0 ");
                    } else {
                        // Print the number of the node just before destination on the shortest path
                        out.print((pMatrix[i][j] != -1 ? (pMatrix[i][j] + 1) : "-") + " ");
                    }
                }
                out.println();
            }
    
            out.println();
    
            // Output shortest paths for each city to all other cities
            for (int source = 0; source < n; source++) {
                out.println("V" + (source + 1) + "-Vj: shortest path and length");
                for (int dest = 0; dest < n; dest++) {
                    // Get the shortest path and distance between the source and destination
                    String path = getShortestPath(source, dest);
                    int distance = adjMatrix[source][dest];
                    out.println(path + ": " + distance);
                }
                out.println();
            }
            out.println(); // Separate problems visually
        }
    }
        
    

    private static String getShortestPath(int source, int dest) {
        if (adjMatrix[source][dest] == Integer.MAX_VALUE) {
            return "No path";
        }
    
        StringBuilder path = new StringBuilder("V" + (source + 1));
        int next = source;
        // Traverse from source to destination using Pmatrix to construct the path
        while (next != dest) {
            next = pMatrix[next][dest];
            if(next == -1) break; // Break if there’s no valid next step (should not happen in a correctly initialized Pmatrix)
            path.append(" V").append(next + 1);
        }
    
        return path.toString();
    }
} Update the logic of Pmatrix such that if there is a direct path form the source node to the destination node then it should be represented by 0. If there is no direct path from the source node to the destination node then find the shortest path between them and print the number of the node which is just before the destination node on the shortest path from source node to destination node. Take reference of the program ﻿

def initialize_matrices(num_vertices, edges):
inf = float('inf")
D= [[inf if i != j else 0 for i in range(num_vertices)] for j in range(num_vertices)] 
P = [[0 if i != j else 0 for i in range(num_vertices)] for j in range(num_vertices)]

for start, end, weight in edges:
D[start][end]= weight 
P[start][end]= start + 1

return D, P

def floyd(num_vertices, edges):
D, P = initialize_matrices(num_vertices, edges)

print_matrix(D, 0, "DO") 
print_matrix(P, 0, "PO")
for k in range(num_vertices):
for i in range(num_vertices): 
for j in range(num_vertices): 
if D[i][k] + D[k][j] <D[i][j]: 
D[i][j] = D[i][k] + D[k][j] 
P[i][j] = P[k][j]
print_matrix(D, k+ 1, f'D{k+1}") 
print_matrix(P, k+1, f'P{k+1}")
return D, P