GT Practical File (Ish)
GT Practical File (Ish)
OBJECTIVE
Program to find the number of vertices, even vertices, odd vertices and number of
edges in a graph
PROGRAM
num_vertices = int(input("Enter the number of vertices: "))
print("Enter the adjacency matrix row by row (use 0 for no edge and 1 for an edge):")
adj_matrix = []
for i in range(num_vertices):
row = list(map(int, input(f"Row {i + 1}: ").split()))
adj_matrix.append(row)
even_vertices = 0
odd_vertices = 0
num_edges = 0
for i in range(num_vertices):
degree = sum(adj_matrix[i]) # Degree of the vertex i is the sum of the row i
num_edges += degree
if degree % 2 == 0:
even_vertices += 1
else:
odd_vertices += 1
num_edges //= 2
print("Number of vertices:", num_vertices)
print("Number of even vertices:", even_vertices)
print("Number of odd vertices:", odd_vertices)
print("Number of edges:", num_edges)
OUTPUT
PRACTICAL-2
OBJECTIVE
Write a Program to find union, Intersection and ring sum of two graphs
PROGRAM
#Getting the vertex set of graph 1 as input
print("\n Enter the vertices in graph 1(separated by space):")
v_g1=list(map(int,input().split()))
OUTPUT
PRACTICAL-3
OBJECTIVE
Write a program to find shortest path between two vertices in a graph using Dijkstra’s
Algorithm.
Program
import heapq
def dijkstra(graph, start, end):
queue = [(0, start)] # (distance, node)
distances = {node: float('inf') for node in graph}
distances[start] = 0
while queue:
dist, node = heapq.heappop(queue)
if node == end:
return dist
for neighbor, weight in graph[node]:
new_dist = dist + weight
if new_dist < distances[neighbor]:
distances[neighbor] = new_dist
heapq.heappush(queue, (new_dist, neighbor))
return float('inf')
graph = {
0: [(1, 4), (2, 1)],
1: [(3, 1)],
2: [(1, 2), (3, 5)],
3: []
}
start = int(input("Enter start node: "))
end = int(input("Enter end node: "))
print("Shortest path distance:", dijkstra(graph, start, end))
OUTPUT
PRACTICAL-4
OBJECTIVE
Write a program to find shortest path between every pair of vertices in a graph using Floyd-
Warshall’s Algorithm.
PROGRAM
# Get the number of vertices from the user
num_vertices = int(input("Enter the number of vertices: "))
# Initialize the adjacency matrix
print("Enter the adjacency matrix (use a large number, like 9999, to represent no direct
path):")
distances = []
for i in range(num_vertices):
row = list(map(int, input(f"Row {i + 1}: ").split()))
distances.append(row)
# Floyd-Warshall Algorithm
for k in range(num_vertices):
for i in range(num_vertices):
for j in range(num_vertices):
# If a shorter path from i to j through k exists, update the distance
distances[i][j] = min(distances[i][j], distances[i][k] + distances[k][j])
# Display the result
print("\nShortest distances between every pair of vertices:")
for i in range(num_vertices):
for j in range(num_vertices):
if distances[i][j] == 9999:
print("INF", end=" ")
else:
print(distances[i][j], end=" ")
print()
OUTPUT
PRACTICAL-5
OBJECTIVE
Write a program to find shortest path between two vertices in a graph using Bellman Ford’s
Algorithm.
PROGRAM
num_vertices = int(input("Enter the number of vertices: "))
num_edges = int(input("Enter the number of edges: "))
edges = []
print("Enter each edge in the format: source destination weight")
for _ in range(num_edges):
u, v, w = map(int, input().split())
edges.append((u, v, w))
source = int(input("Enter the source vertex: "))
destination = int(input("Enter the destination vertex: "))
distances = [float('inf')] * num_vertices
distances[source] = 0
predecessors = [-1] * num_vertices # To store the path
for _ in range(num_vertices - 1):
for u, v, w in edges:
if distances[u] != float('inf') and distances[u] + w < distances[v]:
distances[v] = distances[u] + w
predecessors[v] = u
for u, v, w in edges:
if distances[u] != float('inf') and distances[u] + w < distances[v]:
print("The graph contains a negative-weight cycle.")
exit()
if distances[destination] == float('inf'):
print("There is no path from vertex {} to vertex {}.".format(source, destination))
else:
print("The shortest distance from vertex {} to vertex {} is: {}".format(source, destination,
distances[destination])
path = []
current = destination
while current != -1:
path.append(current)
current = predecessors[current]
path = path[::-1] # Reverse the path to start from the source
print("The shortest path is:", " -> ".join(map(str, path)))
OUTPUT
PRACTICAL-6
OBJECTIVE
Program to find minimal spanning tree of a graph using Prim’s Algorithm
PROGRAM
num_vertices = int(input("Enter the number of vertices: "))
print("Enter the adjacency matrix (use a large number, like 9999, for no direct edge):")
graph = []
for i in range(num_vertices):
row = list(map(int, input(f"Row {i + 1}: ").split()))
graph.append(row)
selected = [False] * num_vertices # Track selected vertices
selected[0] = True # Start from the first vertex
edges = [] # To store the edges of the MST
total_cost = 0 # Cost of the MST
for _ in range(num_vertices - 1): # We need (num_vertices - 1) edges for the MST
min_weight = 9999 # Large initial value to find the minimum edge
u = v = -1
for i in range(num_vertices):
if selected[i]: # Look only at selected vertices
for j in range(num_vertices):
if not selected[j] and graph[i][j] < min_weight: # Check only unselected vertices
min_weight = graph[i][j]
u, v = i, j
if u != -1 and v != -1:
edges.append((u, v, min_weight))
total_cost += min_weight
selected[v] = True # Mark the vertex as selected
print("\nEdges in the Minimum Spanning Tree:")
for u, v, weight in edges:
print(f"{u} -- {v} == {weight}")
print("\nTotal cost of the Minimum Spanning Tree:", total_cost)
OUTPUT
PRACTICAL-7
OBJECTIVE
Program to find minimal spanning tree of a graph using Kruskal’s Algorithm
PROGRAM
def find(parent, i):
while parent[i] != i:
i = parent[i]
return i
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root_y]:
parent[root_y] = root_x
else:
parent[root_y] = root_x
rank[root_x] += 1
num_vertices = int(input("Enter the number of vertices: "))
num_edges = int(input("Enter the number of edges: "))
edges = []
print("Enter each edge in the format: source destination weight")
for _ in range(num_edges):
u, v, w = map(int, input().split())
edges.append((w, u, v)) # Store as (weight, source, destination) for easy sorting
edges.sort()
parent = list(range(num_vertices)) # Parent array for union-find
rank = [0] * num_vertices # Rank array for union-find
mst = [] # Store the edges of the MST
total_cost = 0 # Total cost of the MST
for weight, u, v in edges:
# Find roots of the vertices
root_u = find(parent, u)
root_v = find(parent, v)
# If u and v are in different sets, add the edge to the MST
if root_u != root_v:
mst.append((u, v, weight))
total_cost += weight
union(parent, rank, root_u, root_v)
print("\nEdges in the Minimum Spanning Tree:")
for u, v, weight in mst:
print(f"{u} -- {v} == {weight}")
print("\nTotal cost of the Minimum Spanning Tree:", total_cost)
OUTPUT
PRACTICAL-8
OBJECTIVE
Program to find maximum matching for a bipartite graph
PROGRAM
from collections import deque
def bfs(pair_U, pair_V, dist, U):
queue = deque()
for u in range(U):
if pair_U[u] == -1:
dist[u] = 0
queue.append(u)
else:
dist[u] = float('inf')
dist[-1] = float('inf')
while queue:
u = queue.popleft()
if dist[u] < dist[-1]:
for v in adj[u]:
if dist[pair_V[v]] == float('inf'):
dist[pair_V[v]] = dist[u] + 1
queue.append(pair_V[v])
return dist[-1] != float('inf')
def dfs(u, pair_U, pair_V, dist):
if u != -1:
for v in adj[u]:
if dist[pair_V[v]] == dist[u] + 1:
if dfs(pair_V[v], pair_U, pair_V, dist):
pair_V[v] = u
pair_U[u] = v
return True
dist[u] = float('inf')
return False
return True
def hopcroft_karp(U, V):
pair_U = [-1] * U # Pairing for vertices in U
pair_V = [-1] * V # Pairing for vertices in V
dist = [-1] * (U + 1)
matching = 0
while bfs(pair_U, pair_V, dist, U):
for u in range(U):
if pair_U[u] == -1:
if dfs(u, pair_U, pair_V, dist):
matching += 1
return matching, pair_U
U = int(input("Enter the number of vertices in set U: "))
V = int(input("Enter the number of vertices in set V: "))
adj = [[] for _ in range(U)]
print("Enter the edges between vertices in set U and set V (one per line as 'u v'):")
print("Enter -1 -1 to stop.")
while True:
u, v = map(int, input().split())
if u == -1 and v == -1:
break
adj[u].append(v)
matching, pair_U = hopcroft_karp(U, V)
print("\nThe maximum matching has", matching, "edges.")
print("The matched pairs are:")
for u in range(U):
if pair_U[u] != -1:
print(f"U{u} -- V{pair_U[u]}")
OUTPUT
PRACTICAL-9
OBJECTIVE
Program to find maximum matching for a general graph
PROGRAM
pip install network
import networkx as nx
G = nx.Graph()
num_vertices = int(input("Enter the number of vertices in the graph: "))
num_edges = int(input("Enter the number of edges in the graph: "))
print("Enter each edge in the format: u v")
for _ in range(num_edges):
u, v = map(int, input().split())
G.add_edge(u, v)
matching = nx.max_weight_matching(G, maxcardinality=True)
print("\nThe maximum matching has", len(matching), "edges.")
print("The matched pairs are:")
for u, v in matching:
print(f"{u} -- {v}")
OUTPUT
PRACTICAL-10
OBJECTIVE
Program to find maximum flow from source node to sink node using Ford Fulkerson
Algorithm
PROGRAM
from collections import deque
def bfs(r_graph, source, sink, parent):
visited = [False] * len(r_graph)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v, capacity in enumerate(r_graph[u]):
if not visited[v] and capacity > 0:
parent[v] = u
if v == sink:
return True
queue.append(v)
visited[v] = True
return False
def ford_fulkerson(graph, source, sink):
r_graph = [row[:] for row in graph] # Residual graph
parent = [-1] * len(graph)
max_flow = 0
while bfs(r_graph, source, sink, parent)
path_flow = float('Inf')
s = sink
while s != source:
path_flow = min(path_flow, r_graph[parent[s]][s])
s = parent[s]
v = sink
while v != source:
u = parent[v]
r_graph[u][v] -= path_flow
r_graph[v][u] += path_flow
v = parent[v]
max_flow += path_flow
return max_flow
num_vertices = int(input("Enter number of vertices: "))
print("Enter adjacency matrix:")
graph = [list(map(int, input().split())) for _ in range(num_vertices)]
source = int(input("Enter source node: "))
sink = int(input("Enter sink node: "))
print("Maximum flow:", ford_fulkerson(graph, source, sink))
OUTPUT