alg_lab
alg_lab
Aim:
Algorithm:
o Process v.
If n is not in visited:
Mark n as visited.
Enqueue n into Q.
Code:
import networkx as nx
visited = set()
queue = deque([start])
traversal = []
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
traversal.append(node)
queue.append(neighbor)
return traversal
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
G = nx.DiGraph(graph)
pos = nx.spring_layout(G)
plt.show()
output:
2. Depth First Search (DFS)
Aim:
o Mark v as visited.
o Process v.
4. Call DFS(start).
Code:
if visited is None:
visited = set()
traversal = []
visited.add(node)
traversal.append(node)
return traversal
G = nx.DiGraph(graph)
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.
Code:
import heapq
distances[start] = 0
pq = [(0, start)]
while pq:
curr_dist, u = heapq.heappop(pq)
for v in graph[u]:
weight = graph[u][v]
return distances
weighted_graph = {
'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)
plt.show()
Output:
4. Prim's Algorithm
Aim:
Algorithm:
o If v is not visited:
Add v to visited.
Add all edges from v to heap where the other end is not
visited.
Code:
visited = set([start])
heapq.heapify(edges)
mst = []
while edges:
if to not in visited:
visited.add(to)
return mst
graph_prim = {
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)
plt.show()
Output:
5. Floyd-Warshall Algorithm
Aim:
To compute the shortest paths between all pairs of vertices.
Algorithm:
Code:
def floyd_warshall_plot(graph):
nodes = list(graph.keys())
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:
return dist
fw_graph = {
'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)
plt.show()
result = floyd_warshall_plot(fw_graph)
for i in result:
print(i, result[i])
Output: