Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class solution {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- // takes N = Cities, M = Roads, creates a MATRIX box
- int N = sc.nextInt(), M = sc.nextInt();
- int[][] matrix = new int[N][N];
- for (int i = 0; i < M; i++) {
- matrix[sc.nextInt()][sc.nextInt()] = sc.nextInt();
- }
- int[] d = getShortestPath(matrix, N);
- for (int i = 1; i < d.length; i++) {
- System.out.println(d[i]);
- }
- }
- public static int[] getShortestPath(int[][] mat, int v) {
- int[][] matrix = mat; // contains the graph
- int[] d = new int[v]; // contains the distance
- int[] check = new int[v]; // checks for the visited vertices
- shortPath(matrix, d, check);
- return d;
- }
- public static void shortPath(int[][] matrix, int[] d, int[] check) {
- for (int i = 0; i < matrix.length; i++) {
- d[i] = 999999;
- }
- // Taking source = 0
- d[matrix.length-1] = 0;
- // loop for all vertices
- for (int i = 0; i < matrix.length; i++) {
- int u = minVertex(matrix, d, check);
- for (int v = 0; v < matrix.length; v++) {
- // check for connections
- if (matrix[u][v] != 0 && check[v] != -1) {
- if (d[v] > d[u] + matrix[u][v]) {
- d[v] = d[u] + matrix[u][v];
- }
- // System.out.println(d[v]); // TEST ONLY
- }
- }
- }
- }
- public static int minVertex(int[][] matrix, int[] d, int[] check) {
- int vertex = -1;
- // check for unchecked vertexes
- for (int i = 0; i < matrix.length; i++) {
- if (check[i] != -1) {
- // -1 in check means visited vertex
- vertex = i;
- break;
- }
- }
- // finding the vertex with minimum d
- int minVal = d[vertex];
- if (vertex != -1) {
- for (int i = vertex + 1; i < matrix.length; i++) {
- if (check[i] != -1 && d[i] < minVal) {
- minVal = d[i];
- vertex = i;
- }
- }
- }
- // check vertex to -1, as Visited
- check[vertex] = -1;
- return vertex;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement