ADA Programs
ADA Programs
queue.append(start)
visited.add(start)
while queue:
vertex = queue.pop(0)
print(vertex, end=' ')
for _ in range(num_edges):
# _ is a convention in Python to indicate
# that the loop variable is not going to be
# used within the loop.
u, v = map(int, input("Enter an edge (u v): ").split())
# Check if u and v are within the valid
# range of vertex values
if u <= num_vertices and v <= num_vertices:
add_edge(graph, u, v)
# Ensure that both u and v are in the graph
# to avoid KeyError
add_edge(graph, v, u)
else:
print(f"Invalid edge ({u}, {v}). Vertex values must be between 1
and {num_vertices}.")
return graph
graph = build_graph()
start_vertex = int(input("Enter the starting vertex for BFS: "))
print("BFS traversal starting from vertex", start_vertex, ":")
bfs(graph, start_vertex)
PROGRAM 7
def dfs(graph, start):
visited = set()
stack = []
stack.append(start)
visited.add(start)
while stack:
vertex = stack.pop()
print(vertex, end=' ')
if vertex in graph:
for neighbor in reversed(graph[vertex]):
if neighbor not in visited:
stack.append(neighbor)
visited.add(neighbor)
for _ in range(num_edges):
u, v = map(int, input("Enter an edge (u v): ").split())
return graph
graph = build_graph()
start_vertex = int(input("Enter the starting vertex for DFS: "))
print("DFS traversal starting from vertex", start_vertex, ":")
dfs(graph, start_vertex)
PROGRAM B1
def is_safe(board, row, col, n):
# Checks row-wise if there is a queen in the same column
for i in range(row):
if board[i][col] == 1:
return False
return True
return False
def solve_n_queens(n):
PROGRAM B2
#A recursive function that is used to find subsets of a given set S
# of positive integers whose sum is equal to a specified target sum d
# Below line is used to include the current element from the set S in the
# subset being considered during the recursive exploration of possible
subsets with the desired sum.
subset.append(S[n - 1])
def subset_sum():
S = list(map(int, input("Enter the set of positive integers separated by
spaces: ").split()))
d = int(input("Enter the target sum: "))
n = len(S)
subset_sum()