0% found this document useful (0 votes)
0 views

FloydWarshalAlgoUsingMatrix

The document contains a Java implementation of the Floyd-Warshall algorithm, which calculates the shortest paths between all pairs of nodes in a weighted graph. It initializes a distance matrix with given distances and applies the algorithm through three nested loops to update the distances. Finally, it prints the resulting shortest distance matrix, indicating infinite distances with 'INF'.

Uploaded by

20cse0129
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

FloydWarshalAlgoUsingMatrix

The document contains a Java implementation of the Floyd-Warshall algorithm, which calculates the shortest paths between all pairs of nodes in a weighted graph. It initializes a distance matrix with given distances and applies the algorithm through three nested loops to update the distances. Finally, it prints the resulting shortest distance matrix, indicating infinite distances with 'INF'.

Uploaded by

20cse0129
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.util.

Arrays;

public class FloydWarshallMatrix {


static final int INF = 99999; // Use a large number to represent infinity

public static void main(String[] args) {


// Initial distance matrix
int[][] dist = {
{0, 3, INF, 7},
{8, 0, 2, INF},
{5, INF, 0, 1},
{2, INF, INF, 0}
};

// Number of nodes (villages)


int n = dist.length;

// Apply Floyd-Warshall Algorithm


for (int k = 0; k < n; k++) { // Intermediate node
for (int i = 0; i < n; i++) { // Source node
for (int j = 0; j < n; j++) { // Destination node
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}

// Print the final distance matrix


System.out.println("Shortest distances between every pair of vertices:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][j] == INF) {
System.out.print("INF ");
} else {
System.out.print(dist[i][j] + " ");
}
}
System.out.println();
}
}
}

You might also like