import java.util.*; 
 
public class ShortestPath { 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter number of vertices: "); 
        int n = sc.nextInt(); 
        System.out.println("Enter the adjacency matrix: "); 
        int[][] g = new int[n][n]; 
        for (int i = 0; i < n; i++) { 
            for (int j = 0; j < n; j++) { 
                g[i][j] = sc.nextInt(); 
            } 
        } 
 
        System.out.println("Enter source vertex: "); 
        int v = sc.nextInt(); 
        dijkstras(v, g, n); 
    } 
 
    public static void dijkstras(int v, int[][] cost, int n) { 
        boolean[] s = new boolean[n]; 
        int[] dist = new int[n]; 
        for (int i = 0; i < n; i++) { 
            dist[i] = cost[v][i] == 0 ? Integer.MAX_VALUE : cost[v][i]; 
            s[i] = false; 
        } 
 
        s[v] = true; 
        dist[v] = 0; 
 
        for (int i = 1; i < n - 1; i++) { 
            int u = minDist(dist, s); 
            s[u] = true; 
 
            for (int w = 0; w < n; w++) { 
                if (!s[w] && cost[u][w] != 0) { 
                    if (dist[w] > dist[u] + cost[u][w]) { 
                        dist[w] = dist[u] + cost[u][w]; 
                    } 
                } 
            } 
        } 
 
        System.out.println("Shortest distances from source " + v + " :"); 
        for (int i = 0; i < n; i++) { 
            System.out.println("To node " + i + " - Distance : " + dist[i]); 
        } 
    } 
 
    private static int minDist(int[] dis, boolean[] s) { 
        int min = Integer.MAX_VALUE, idx = -1; 
 
        for (int i = 0; i < dis.length; i++) { 
            if (!s[i] && dis[i] <= min) { 
                min = dis[i]; 
                idx = i; 
            } 
        } 
        return idx; 
    } 
}