Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Mayank Tailor 202312052

Algorithms
Assignment - 8
Mayank Tailor
202312052

Dijkstra's shortest path algorithm


Code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class GraphVertices {

// Method to find the shortest path using Dijkstra's algorithm


private static Map<Integer, Integer> dijkstra(int startVertex, int numVertices,
Connection conn) throws SQLException {
Map<Integer, Integer> distance = new HashMap<>();
Set<Integer> visited = new HashSet<>();

// Initialize distance map with infinity for all vertices except the start vertex
for (int i = 1; i <= numVertices; i++) {
distance.put(i, Integer.MAX_VALUE);
}
distance.put(startVertex, 0);

// Dijkstra's algorithm
for (int i = 0; i < numVertices; i++) {
int currentVertex = -1;
int shortestDistance = Integer.MAX_VALUE;
for (int vertex : distance.keySet()) {
if (!visited.contains(vertex) && distance.get(vertex) < shortestDistance) {
currentVertex = vertex;
Mayank Tailor 202312052

shortestDistance = distance.get(vertex);
}
}

if (currentVertex == -1) {
break; // No more vertices to visit
}

visited.add(currentVertex);

// Update distances for adjacent vertices


String getEdgesQuery = "SELECT destination_id, weight FROM edges WHERE
source_id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(getEdgesQuery)) {
pstmt.setInt(1, currentVertex);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
int destination = rs.getInt("destination_id");
int weight = rs.getInt("weight");
if (!visited.contains(destination) && distance.get(currentVertex) + weight
< distance.get(destination)) {
distance.put(destination, distance.get(currentVertex) + weight);
}
}
}
}
}

return distance;
}

public static void main(String[] args) {


// Database credentials
String url = "jdbc:mysql://localhost:3306/dijkstra_10";
String username = "root";
String password = "";

try (Scanner scanner = new Scanner(System.in)) {


// Connect to the database
Mayank Tailor 202312052

try (Connection conn = DriverManager.getConnection(url, username, password))


{
System.out.println("Connected to the database.");

// Get number of vertices from user


System.out.print("Enter number of vertices: ");
int numVertices = scanner.nextInt();

// Insert vertices into the database


String insertVertexQuery = "INSERT INTO vertices (id) VALUES (?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertVertexQuery)) {
for (int i = 1; i <= numVertices; i++) {
pstmt.setInt(1, i);
pstmt.executeUpdate();
}
System.out.println("Vertices added successfully.");

// Generate edges
String insertEdgeQuery = "INSERT INTO edges (source_id, destination_id,
weight) VALUES (?, ?, ?)";
try (PreparedStatement edgePstmt =
conn.prepareStatement(insertEdgeQuery)) {
for (int i = 1; i <= numVertices; i++) {
for (int j = 1; j <= numVertices; j++) {
int weight = (int) (Math.random() * 10) + 1; // Generate random
weight between 1 and 10
int randomNum = (int) (Math.random() * 10) + 1; // Generate
random number between 1 and 10
if (randomNum >= 8 && i != j) { // 30% probability of adding an edge
edgePstmt.setInt(1, i);
edgePstmt.setInt(2, j);
edgePstmt.setInt(3, weight);
edgePstmt.executeUpdate();
}
}
}
System.out.println("Edges added successfully.");

// Example: Find shortest path from vertex 1 to all other vertices


int startVertex = 1;
Mayank Tailor 202312052

Map<Integer, Integer> shortestDistances = dijkstra(startVertex,


numVertices, conn);
for (int vertex : shortestDistances.keySet()) {
System.out.println("Shortest distance from vertex " + startVertex + " to
vertex " + vertex + ": " + shortestDistances.get(vertex));
}
} catch (SQLException e) {
System.out.println("Error inserting edges: " + e.getMessage());
}
} catch (SQLException e) {
System.out.println("Error inserting vertices: " + e.getMessage());
}

} catch (SQLException e) {
System.out.println("Connection failed: " + e.getMessage());
}
}
}
}
Output:
Mayank Tailor 202312052

A.Validate your algorithm manually with small-size graphs.


Mayank Tailor 202312052

B. After the algorithm has been validated, run it on progressively


larger graphs and plot the running times

->Input 10 : 66 milliseconds

->Input 50 : 119 milliseconds

->Input 50 : 225 milliseconds


Mayank Tailor 202312052

Complexity = (V lg V)

You might also like