Kompyuter injeneringi


Bellman-Ford algoritmi dasturi



Yüklə 52,37 Kb.
səhifə2/3
tarix07.01.2024
ölçüsü52,37 Kb.
#202644
1   2   3
5 amaliy topshiriq

Bellman-Ford algoritmi dasturi:

import java.util.*;

class Graph {
private int vertexCount;
private List> adjacencyList;

public Graph(int vertexCount) {


this.vertexCount = vertexCount;
adjacencyList = new ArrayList<>(vertexCount);
for (int i = 0; i < vertexCount; i++) {
adjacencyList.add(new ArrayList<>());
}
}

public void addEdge(int source, int destination, int weight) {


adjacencyList.get(source).add(new Edge(destination, weight));
}

public int[] dijkstra(int source) {


int[] distances = new int[vertexCount];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[source] = 0;

PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(node -> node.distance));


pq.add(new Node(source, 0));

while (!pq.isEmpty()) {


Node current = pq.poll();
int vertex = current.vertex;
int distance = current.distance;

if (distance > distances[vertex]) {


continue;
}

for (Edge edge : adjacencyList.get(vertex)) {


int newDistance = distance + edge.weight;
if (newDistance < distances[edge.destination]) {
distances[edge.destination] = newDistance;
pq.add(new Node(edge.destination, newDistance));
}
}
}

return distances;


}

private static class Edge {


private int destination;
private int weight;

public Edge(int destination, int weight) {


this.destination = destination;
this.weight = weight;
}
}

private static class Node {


private int vertex;
private int distance;

public Node(int vertex, int distance) {


this.vertex = vertex;
this.distance = distance;
}
}
}

public class DijkstraAlgorithm {


public static void main(String[] args) {
Graph graph = new Graph(6);

graph.addEdge(0, 1, 2);


graph.addEdge(0, 2, 4);
graph.addEdge(1, 3, 7);
graph.addEdge(1, 4, 3);
graph.addEdge(2, 4, 1);
graph.addEdge(3, 4, 5);
graph.addEdge(3, 5, 2);

int[] distances = graph.dijkstra(0);



System.out.println("Shortest distances from source vertex 0:");
for (int i = 0; i < distances.length; i++) {
System.out.println("Vertex " + i + ": " + distances[i]);
}
}
}

Yüklə 52,37 Kb.

Dostları ilə paylaş:
1   2   3




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin