aipr8ka
aipr8ka
if __name__ == "__main__":
main()
Practical - 9
import heapq
class Node:
def __init__(self, state, parent=None, g=0, h=0):
self.state = state
self.parent = parent
self.g = g # Cost from start to this node
self.h = h # Heuristic cost estimate to goal
self.f = g + h # Total cost (f = g + h)
while open_set:
current_node = heapq.heappop(open_set)
if current_node.state == goal:
path = []
while current_node:
path.append(current_node.state)
current_node = current_node.parent
return path[::-1] # Return reversed path
closed_set.add(current_node.state)
return None
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def get_neighbors(state):
x, y = state
neighbors = []
for dx, dy, cost in [(-1, 0, 1), (1, 0, 1), (0, -1, 1), (0, 1, 1)]:
nx, ny = x + dx, y + dy
neighbors.append(((nx, ny), cost))
return neighbors
start = (0, 0)
goal = (3, 3)
path = a_star(start, goal, get_neighbors, heuristic)
if path:
print("Path found:", path)
else:
print("No path found")
Practical - 12
import sys
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
if root_u != root_v:
if self.rank[root_u] > self.rank[root_v]:
self.parent[root_v] = root_u
elif self.rank[root_u] < self.rank[root_v]:
self.parent[root_u] = root_v
else:
self.parent[root_v] = root_u
self.rank[root_u] += 1
def prim_mst(graph):
num_vertices = len(graph)
key = [sys.maxsize] * num_vertices # Initialize keys as infinite
parent = [None] * num_vertices # Array to store constructed MST
mst_set = [False] * num_vertices # To track vertices included in MST
for _ in range(num_vertices):
# Find the vertex with the minimum key value that is not yet included in the MST
min_key = sys.maxsize
min_index = -1
for v in range(num_vertices):
if not mst_set[v] and key[v] < min_key:
min_key = key[v]
min_index = v
u = min_index
mst_set[u] = True # Add the vertex to the MST
# Update key values and parent index of the adjacent vertices of the picked vertex
for v in range(num_vertices):
if graph[u][v] and not mst_set[v] and graph[u][v] < key[v]:
key[v] = graph[u][v]
parent[v] = u
ds = DisjointSet(vertices)
mst = []
mst_weight = 0
def main():
print("Select the algorithm:")
print("1. Prim's Algorithm")
print("2. Kruskal's Algorithm")
choice = input("Enter your choice (1 or 2): ").strip()
if choice == '1':
graph = [
[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]
]
prim_mst(graph)
elif choice == '2':
vertices = 5
edges = [
(0, 1, 2),
(1, 2, 3),
(2, 4, 7),
(4, 3, 9),
(0, 3, 6),
(1, 4, 5)
]
kruskal_mst(vertices, edges)
else:
print("Invalid choice!")
if __name__ == "__main__":
main()