|
Floyd-Warshall algoritmi dasturi
|
səhifə | 3/3 | tarix | 07.01.2024 | ölçüsü | 52,37 Kb. | | #202644 |
| 5 amaliy topshiriq
Floyd-Warshall algoritmi dasturi:
import java.util.Arrays;
public class FloydWarshallAlgorithm {
private static final int INF = Integer.MAX_VALUE;
public static void floydWarshall(int[][] graph) {
int vertexCount = graph.length;
int[][] distances = new int[vertexCount][vertexCount];
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
distances[i][j] = graph[i][j];
}
}
for (int k = 0; k < vertexCount; k++) {
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
if (distances[i][k] != INF && distances[k][j] != INF && distances[i][k] + distances[k][j] < distances[i][j]) {
distances[i][j] = distances[i][k] + distances[k][j];
}
}
}
}
System.out.println("Shortest distances between all pairs of vertices:");
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
if (distances[i][j] == INF) {
System.out.print("INF ");
} else {
System.out.print(distances[i][j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 2, 4, INF, INF, INF},
{INF, 0, INF, 7, 3, INF},
{INF, INF, 0, INF, 1, INF},
{INF, INF, INF, 0, 5, 2},
{INF, INF, INF, INF, 0, INF},
{INF, INF, INF, INF, INF, 0}
};
floydWarshall(graph);
}
}
Dostları ilə paylaş: |
|
|