Professional Documents
Culture Documents
Algo Lab8
Algo Lab8
Algorithms
Assignment - 8
Mayank Tailor
202312052
// 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);
return distance;
}
// 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.");
} catch (SQLException e) {
System.out.println("Connection failed: " + e.getMessage());
}
}
}
}
Output:
Mayank Tailor 202312052
->Input 10 : 66 milliseconds
Complexity = (V lg V)