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

from collections import defaultdict, deque

import heapq

# Initialize global variables


graph = defaultdict(list)

def add_vertices(v):
if v not in graph:
graph[v] = []

def add_edges(v1, v2, c):


if v1 not in graph or v2 not in graph:
print("Enter valid vertices for the edge")
else:
graph[v1].append((v2, c))
graph[v2].append((v1, c)) # Assuming it's an undirected graph

def print_graph():
for v in graph:
print(f"Vertex {v} -> ", end="")
for edge in graph[v]:
print(f"{edge[0]} (edge weight {edge[1]})", end=", ")
print()

def delete_vertex(v):
if v in graph:
del graph[v]
for vertex in graph:
graph[vertex] = [(neighbor, cost) for neighbor, cost in graph[vertex] if neighbor !=
v]
else:
print(f"Vertex {v} not found in the graph.")

def delete_edge(v1, v2):


if v1 in graph and v2 in graph:
graph[v1] = [(neighbor, cost) for neighbor, cost in graph[v1] if neighbor != v2]
graph[v2] = [(neighbor, cost) for neighbor, cost in graph[v2] if neighbor != v1]
else:
print("Vertices not found in the graph.")

def bfs(start_vertex, end_vertex):


if start_vertex not in graph:
print(f"Vertex {start_vertex} not found in the graph.")
return
if end_vertex not in graph:
print(f"Vertex {end_vertex} not found in the graph.")
return

visited = set()
queue = deque([start_vertex])
visited.add(start_vertex)

print("BFS Traversal:")
while queue:
vertex = queue.popleft()
print(vertex, end=" ")

if vertex == end_vertex:
print(f"\nReached the end vertex {end_vertex}.")
return

for neighbor, _ in graph[vertex]:


if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
print("\nEnd vertex not reachable from the start vertex.")

def dfs(start_vertex, end_vertex):


if start_vertex not in graph:
print(f"Vertex {start_vertex} not found in the graph.")
return
if end_vertex not in graph:
print(f"Vertex {end_vertex} not found in the graph.")
return

visited = set()
stack = [start_vertex] # Store vertices to visit
visited.add(start_vertex)

print("DFS Traversal:")
while stack:
vertex = stack.pop()
print(vertex, end=" ")

if vertex == end_vertex:
print(f"\nReached the end vertex {end_vertex}.")
return

for neighbor, _ in graph[vertex]:


if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)

print("\nEnd vertex not reachable from the start vertex.")

def ucs(start_vertex, end_vertex):


if start_vertex not in graph:
print(f"Vertex {start_vertex} not found in the graph.")
return
if end_vertex not in graph:
print(f"Vertex {end_vertex} not found in the graph.")
return

priority_queue = [(0, start_vertex)] # Store (path_cost, vertex)


visited = set()
path_cost = {start_vertex: 0}
parent = {start_vertex: None}
while priority_queue:
cost, vertex = heapq.heappop(priority_queue)

if vertex == end_vertex:
print(f"UCS Path Cost from {start_vertex} to {end_vertex}:
{path_cost[end_vertex]}")
print(f"UCS Path:")
print_path(parent, end_vertex)
return

if vertex not in visited:


visited.add(vertex)

for neighbor, edge_cost in graph[vertex]:


if neighbor not in visited:
new_cost = cost + edge_cost
if neighbor not in path_cost or new_cost < path_cost[neighbor]:
path_cost[neighbor] = new_cost
parent[neighbor] = vertex
heapq.heappush(priority_queue, (new_cost, neighbor))

print("\nEnd vertex not reachable from the start vertex.")

def print_path(parent, vertex):


if parent[vertex] is not None:
print_path(parent, parent[vertex])
print(vertex, end=" -> ")

def construct_graph():
global graph
graph.clear() # Clear existing graph data
n = int(input("Enter number of vertices: "))
for i in range(n):
v = int(input(f"Enter vertex {i + 1}: "))
add_vertices(v)

e = int(input("Enter number of edges: "))


print("Enter edges (v1, v2, cost):")
for j in range(e):
v1, v2, cost = map(int, input(f"Edge {j + 1}: ").split(","))
add_edges(v1, v2, cost)

print("Adjacency List Representation of Graph:")


print_graph()

def main():
while True:
print("\nMenu:")
print("1. Construct graph")
print("2. Add vertex")
print("3. Add edge")
print("4. Delete vertex")
print("5. Delete edge")
print("6. Print graph")
print("7. Perform BFS traversal")
print("8. Perform DFS traversal")
print("9. Perform UCS (Uniform Cost Search)")
print("10. Exit")

choice = input("Enter your choice: ")

if choice == '1':
construct_graph()
elif choice == '2':
v = int(input("Enter vertex to add: "))
add_vertices(v)
elif choice == '3':
v1, v2, cost = map(int, input("Enter edge (v1, v2, cost): ").split(","))
add_edges(v1, v2, cost)
elif choice == '4':
v = int(input("Enter vertex to delete: "))
delete_vertex(v)
elif choice == '5':
v1, v2 = map(int, input("Enter edge to delete (v1, v2): ").split(","))
delete_edge(v1, v2)
elif choice == '6':
print("Adjacency List Representation of Graph:")
print_graph()
elif choice == '7':
start_vertex = int(input("Enter the start vertex for BFS: "))
end_vertex = int(input("Enter the end vertex for BFS: "))
bfs(start_vertex, end_vertex)
elif choice == '8':
start_vertex = int(input("Enter the start vertex for DFS: "))
end_vertex = int(input("Enter the end vertex for DFS: "))
dfs(start_vertex, end_vertex)
elif choice == '9':
start_vertex = int(input("Enter the start vertex for UCS: "))
end_vertex = int(input("Enter the end vertex for UCS: "))
ucs(start_vertex, end_vertex)
elif choice == '10':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a valid option.")

if __name__ == "__main__":
main()

You might also like