0% found this document useful (0 votes)
22 views5 pages

ADA Programs

The document contains multiple Python programs for graph traversal and solving combinatorial problems. It includes implementations for Breadth-First Search (BFS) and Depth-First Search (DFS) on graphs, as well as solutions for the N-Queens problem and finding subsets that sum to a target value. Each program accepts user input to build the graph or define the problem parameters and outputs the results accordingly.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views5 pages

ADA Programs

The document contains multiple Python programs for graph traversal and solving combinatorial problems. It includes implementations for Breadth-First Search (BFS) and Depth-First Search (DFS) on graphs, as well as solutions for the N-Queens problem and finding subsets that sum to a target value. Each program accepts user input to build the graph or define the problem parameters and outputs the results accordingly.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

PROGRAM 6:

# Function to perform BFS on the graph starting


#from a given start vertex.
def bfs(graph, start):
# visited is a set that keeps track of
# visited vertices to avoid revisiting them.
visited = set()
# queue is a list used as a queue data structure.
# It starts with the start vertex and is
# used to store vertices to be visited
# in the order they are dequeued.
queue = []

queue.append(start)
visited.add(start)

while queue:
vertex = queue.pop(0)
print(vertex, end=' ')

# iterating through the neighbors of the current


# vertex in the graph and adding them to the BFS
# queue if they haven't been visited yet.
if vertex in graph:
for neighbor in graph[vertex]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)

# Function to add an edge to the graph


def add_edge(graph, u, v):
if u in graph:
graph[u].append(v)
else:
graph[u] = [v]

# Function to accept inputs and build the graph


def build_graph():
graph = {}
num_vertices = int(input("Enter the number of vertices: "))
num_edges = int(input("Enter the number of edges: "))

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)

# Function to add an edge to the graph


def add_edge(graph, u, v):
if u in graph:
graph[u].append(v)
else:
graph[u] = [v]

# Function to accept inputs and build the graph


def build_graph():
graph = {}
num_vertices = int(input("Enter the number of vertices: "))
num_edges = int(input("Enter the number of edges: "))

for _ in range(num_edges):
u, v = map(int, input("Enter an edge (u v): ").split())

if 1 <= u <= num_vertices and 1 <= v <= num_vertices:


add_edge(graph, u, v)
# Do not add the reverse edge since it's a
# directed DFS.
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 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

# Check upper left diagonal


for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check upper right diagonal


for i, j in zip(range(row, -1, -1), range(col, n)):
if board[i][j] == 1:
return False

return True

def solve_n_queens_util(board, row, n):


if row == n:
return True
for col in range(n):
if is_safe(board, row, col, n):
board[row][col] = 1
if solve_n_queens_util(board, row + 1, n):
return True
board[row][col] = 0

return False

def solve_n_queens(n):

board = [[0 for _ in range(n)] for _ in range(n)]


if solve_n_queens_util(board, 0, n):
for row in board:
print(' '.join(['Q' if x == 1 else '.' for x in row]))
print()
else:
print("Solution does not exist")

N = int(input(("Enter the number of queens: ")))


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

def find_subset_sum(S, n, d, subset=[]):


# Base case
if d == 0:
print("Solution found:", subset)
return
if n == 0 or d < 0:
return

# Include the current element

# 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])

find_subset_sum(S, n - 1, d - S[n - 1], subset)


subset.pop() # Backtrack

# Exclude the current element


find_subset_sum(S, n - 1, d, subset)

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)

print("Possible subsets with a sum of", d, "are:")


find_subset_sum(S, n, d)

subset_sum()

You might also like