0% found this document useful (0 votes)
6 views14 pages

alg_lab

The document outlines five graph traversal and pathfinding algorithms: Breadth First Search (BFS), Depth First Search (DFS), Dijkstra's Algorithm, Prim's Algorithm, and Floyd-Warshall Algorithm. Each algorithm includes its aim, a step-by-step algorithm description, and corresponding Python code for implementation using the NetworkX library. The document provides visualizations for each algorithm's graph representation and outputs the results of the traversals or path calculations.

Uploaded by

Jai Surya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

alg_lab

The document outlines five graph traversal and pathfinding algorithms: Breadth First Search (BFS), Depth First Search (DFS), Dijkstra's Algorithm, Prim's Algorithm, and Floyd-Warshall Algorithm. Each algorithm includes its aim, a step-by-step algorithm description, and corresponding Python code for implementation using the NetworkX library. The document provides visualizations for each algorithm's graph representation and outputs the results of the traversals or path calculations.

Uploaded by

Jai Surya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1.

Breadth First Search (BFS)

Aim:

To traverse a graph using Breadth First Search.

Algorithm:

1. Input: Graph G as an adjacency list, and source node start.

2. Initialize an empty set visited to keep track of visited nodes.

3. Create an empty queue Q.

4. Mark start as visited and enqueue it into Q.

5. While Q is not empty:

o Dequeue a node v from Q.

o Process v.

o For each neighbor n of v:

 If n is not in visited:

 Mark n as visited.

 Enqueue n into Q.

6. Repeat until the queue is empty.

Code:

import networkx as nx

import matplotlib.pyplot as plt

from collections import deque

def bfs_plot(graph, start):

visited = set()

queue = deque([start])

traversal = []

while queue:

node = queue.popleft()
if node not in visited:

visited.add(node)

traversal.append(node)

for neighbor in graph[node]:

if neighbor not in visited:

queue.append(neighbor)

return traversal

graph = {

'A': ['B', 'C'],

'B': ['D', 'E'],

'C': ['F'],

'D': [],

'E': ['F'],

'F': []

G = nx.DiGraph(graph)

pos = nx.spring_layout(G)

nx.draw(G, pos, with_labels=True, node_color='skyblue',


node_size=1200, edge_color='gray')

plt.title("Graph for BFS")

plt.show()

print("BFS Traversal:", bfs_plot(graph, 'A'))

output:
2. Depth First Search (DFS)

Aim:

To traverse a graph using Depth First Search.


Algorithm:

1. Input: Graph G and starting node start.

2. Create an empty set visited.

3. Define a recursive function DFS(v):

o Mark v as visited.

o Process v.

o For each neighbor n of v:

 If n is not in visited, call DFS(n).

4. Call DFS(start).

Code:

def dfs_plot(graph, node, visited=None, traversal=None):

if visited is None:

visited = set()

traversal = []

visited.add(node)

traversal.append(node)

for neighbor in graph[node]:

if neighbor not in visited:

dfs_plot(graph, neighbor, visited, traversal)

return traversal

G = nx.DiGraph(graph)

nx.draw(G, pos, with_labels=True, node_color='lightgreen',


node_size=1200, edge_color='black')

plt.title("Graph for DFS")

plt.show()
print("DFS Traversal:", dfs_plot(graph, 'A'))

output:

3. Dijkstra's Algorithm

Aim:

To find the shortest path from a source to all vertices in a weighted graph.

Algorithm:
1. Input: Weighted graph G, and source vertex start.

2. Set all distances to ∞ except the source (0).

3. Use a priority queue (min-heap) pq.

4. Add (0, start) to pq.

5. While pq is not empty:

o Pop (current_distance, u) from pq.

o For each neighbor v of u with weight w:

 If current_distance + w < distance[v], update


distance[v] and push (distance[v], v) to pq.

6. Return the distance dictionary.

Code:

import heapq

def dijkstra_plot(graph, start):

distances = {v: float('inf') for v in graph}

distances[start] = 0

pq = [(0, start)]

while pq:

curr_dist, u = heapq.heappop(pq)

for v in graph[u]:

weight = graph[u][v]

if curr_dist + weight < distances[v]:

distances[v] = curr_dist + weight

heapq.heappush(pq, (distances[v], v))

return distances

weighted_graph = {

'A': {'B': 1, 'C': 4},

'B': {'C': 2, 'D': 5},


'C': {'D': 1},

'D': {}

G = nx.DiGraph()

for u in weighted_graph:

for v in weighted_graph[u]:

G.add_edge(u, v, weight=weighted_graph[u][v])

pos = nx.spring_layout(G)

labels = nx.get_edge_attributes(G, 'weight')

nx.draw(G, pos, with_labels=True, node_color='orange',


node_size=1200, edge_color='black')

nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.title("Graph for Dijkstra's Algorithm")

plt.show()

print("Shortest distances from A:", dijkstra_plot(weighted_graph,


'A'))

Output:
4. Prim's Algorithm
Aim:

To find the Minimum Spanning Tree (MST) of a graph using Prim's


algorithm.

Algorithm:

1. Input: Undirected weighted graph G and a starting node start.

2. Initialize a set visited with start.

3. Create a min-heap with all edges from start.

4. While the number of visited nodes is less than total nodes:

o Extract the minimum weight edge (weight, u, v) from the


heap.

o If v is not visited:

 Add v to visited.

 Add (u, v, weight) to the MST result.

 Add all edges from v to heap where the other end is not
visited.

5. Return MST edges.

Code:

def prim_plot(graph, start):

visited = set([start])

edges = [(cost, start, to) for to, cost in graph[start].items()]

heapq.heapify(edges)

mst = []

while edges:

cost, frm, to = heapq.heappop(edges)

if to not in visited:

visited.add(to)

mst.append((frm, to, cost))

for neighbor, weight in graph[to].items():


if neighbor not in visited:

heapq.heappush(edges, (weight, to, neighbor))

return mst

graph_prim = {

'A': {'B': 2, 'C': 3},

'B': {'A': 2, 'C': 1, 'D': 1},

'C': {'A': 3, 'B': 1, 'D': 4},

'D': {'B': 1, 'C': 4}

G = nx.Graph()

for u in graph_prim:

for v in graph_prim[u]:

G.add_edge(u, v, weight=graph_prim[u][v])

pos = nx.spring_layout(G)

labels = nx.get_edge_attributes(G, 'weight')

nx.draw(G, pos, with_labels=True, node_color='pink', node_size=1200)

nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.title("Graph for Prim's Algorithm")

plt.show()

print("MST (Prim):", prim_plot(graph_prim, 'A'))

Output:
5. Floyd-Warshall Algorithm

Aim:
To compute the shortest paths between all pairs of vertices.

Algorithm:

1. Input: A graph represented as an adjacency matrix or dict of dicts.

2. Create a 2D distance matrix from the graph.

3. For each intermediate vertex k:

o For each source vertex i:

 For each destination vertex j:

 Update distance[i][j] = min(distance[i][j],


distance[i][k] + distance[k][j])

4. Return the final distance matrix.

Code:

def floyd_warshall_plot(graph):

nodes = list(graph.keys())

dist = {i: {j: float('inf') for j in nodes} for i in nodes}

for i in nodes:

dist[i][i] = 0

for j in graph[i]:

dist[i][j] = graph[i][j]

for k in nodes:

for i in nodes:

for j in nodes:

if dist[i][j] > dist[i][k] + dist[k][j]:

dist[i][j] = dist[i][k] + dist[k][j]

return dist

fw_graph = {

'A': {'B': 3, 'C': 8, 'E': -4},

'B': {'D': 1, 'E': 7},

'C': {'B': 4},


'D': {'A': 2, 'C': -5},

'E': {'D': 6}

G = nx.DiGraph()

for u in fw_graph:

for v in fw_graph[u]:

G.add_edge(u, v, weight=fw_graph[u][v])

pos = nx.spring_layout(G)

labels = nx.get_edge_attributes(G, 'weight')

nx.draw(G, pos, with_labels=True, node_color='lightblue',


node_size=1200)

nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.title("Graph for Floyd-Warshall Algorithm")

plt.show()

result = floyd_warshall_plot(fw_graph)

print("All-Pairs Shortest Paths (Floyd-Warshall):")

for i in result:

print(i, result[i])
Output:

You might also like