Ds 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Date: Exp. No.: Page No.

Aim:

Program:

import heapq

import time

import sys

# Dijkstra's algorithm using adjacency matrix

def dijkstra_matrix(graph, src):

V = len(graph)

dist = [sys.maxsize] * V

dist[src] = 0

visited = [False] * V

for _ in range(V):

# Pick the minimum distance vertex from the set of vertices

u = min_distance(dist, visited)

visited[u] = True

# Update dist value of the adjacent vertices of the picked vertex

for v in range(V):

if graph[u][v] > 0 and not visited[v] and dist[u] + graph[u][v] < dist[v]:

dist[v] = dist[u] + graph[u][v]

return dist

# Helper function to find the vertex with minimum distance

Advanced Data structures and algorithm analysis laboratory


Date: Exp. No.: Page No.:
def min_distance(dist, visited):

min_val = sys.maxsize

min_index = -1

for v in range(len(dist)):

if dist[v] < min_val and not visited[v]:

min_val = dist[v]

min_index = v

return min_index

# Dijkstra's algorithm using adjacency list and a priority queue (min-heap)

def dijkstra_list(graph, src):

V = len(graph)

dist = [sys.maxsize] * V

dist[src] = 0

pq = [(0, src)] # (distance, vertex)

while pq:

current_dist, u = heapq.heappop(pq)

if current_dist > dist[u]:

continue

for neighbor, weight in graph[u]:

distance = current_dist + weight

if distance < dist[neighbor]:

Advanced Data structures and algorithm analysis laboratory


Date: Exp. No.: Page No.:
dist[neighbor] = distance

heapq.heappush(pq, (distance, neighbor))

return dist

# Function to compare performance

def compare_performance(V):

# Create random graph as adjacency matrix

import random

random.seed(42)

matrix = [[0 if i == j else random.randint(1, 10) if random.random() < 0.5 else 0 for j in range(V)] for i in
range(V)]

# Create adjacency list from adjacency matrix

adj_list = [[] for _ in range(V)]

for i in range(V):

for j in range(V):

if matrix[i][j] != 0:

adj_list[i].append((j, matrix[i][j]))

src = 0

# Measure performance of Dijkstra's algorithm using adjacency matrix

start = time.time()

dijkstra_matrix(matrix, src)

matrix_time = time.time() - start

Advanced Data structures and algorithm analysis laboratory


Date: Exp. No.: Page No.:
# Measure performance of Dijkstra's algorithm using adjacency list

start = time.time()

dijkstra_list(adj_list, src)

list_time = time.time() - start

print(f"Time taken by adjacency matrix: {matrix_time:.6f} seconds")

print(f"Time taken by adjacency list: {list_time:.6f} seconds")

# Example usage:

compare_performance(750)

Advanced Data structures and algorithm analysis laboratory

You might also like