📅  最后修改于: 2023-12-03 14:58:31.530000             🧑  作者: Mango
This article covers the topics related to Chapter 55 of the GATE CS 2017 question paper. It focuses on the concepts of Graph Theory, particularly on the topic of shortest paths.
A shortest path is defined as the path with minimum weight between a pair of vertices in a graph. There are various algorithms used to find the shortest path in a graph, some of which are:
Dijkstra's algorithm is a greedy algorithm used to find the shortest path between a source node and all other nodes in a weighted graph. It works by assigning a tentative distance to every node in the graph, which is initially set to infinity for all nodes except the source node. It then iteratively selects the node with the minimum tentative distance and updates the distance of all its adjacent nodes. The process continues until the destination node is reached.
public void dijkstra(Graph graph, Vertex source) {
Set<Vertex> visited = new HashSet<>();
PriorityQueue<Vertex> queue = new PriorityQueue<>();
source.distance = 0;
queue.offer(source);
while (!queue.isEmpty()) {
Vertex current = queue.poll();
visited.add(current);
for (Edge edge : current.edges) {
Vertex adjacent = edge.target;
if (!visited.contains(adjacent)) {
int newDist = current.distance + edge.weight;
if (newDist < adjacent.distance) {
queue.remove(adjacent);
adjacent.distance = newDist;
adjacent.previous = current;
queue.offer(adjacent);
}
}
}
}
}
The Bellman-Ford algorithm is another algorithm used to find the shortest path between a source node and all other nodes in a weighted graph. It works by relaxing all the edges in the graph n-1 times, where n is the number of nodes in the graph. A relaxed edge is an edge that is used to update the distance of its target node from the source node. During each iteration, the algorithm checks for negative-weight cycles in the graph.
public void bellmanFord(Graph graph, Vertex source) {
source.distance = 0;
for (int i = 0; i < graph.vertices.size() - 1; i++) {
for (Edge edge : graph.edges) {
Vertex u = edge.source;
Vertex v = edge.target;
if (u.distance + edge.weight < v.distance) {
v.distance = u.distance + edge.weight;
v.previous = u;
}
}
}
for (Edge edge : graph.edges) {
if (edge.source.distance + edge.weight < edge.target.distance) {
throw new RuntimeException("Negative-weight cycle detected");
}
}
}
Both Dijkstra's algorithm and the Bellman-Ford algorithm have a time complexity of O(E log V) and O(VE), respectively, where E is the number of edges and V is the number of vertices in the graph.
In this article, we have covered the various algorithms used to find the shortest path in a graph, along with their implementations in Java. These algorithms are important in the field of computer science and are commonly used in various applications, such as network routing, GPS navigation, and social network analysis.