You are on page 1of 6

Bachelor of Computer Applications

Practical File
For

Course Name: Artificial Intelligence Lab

Course Code: 13480320

Semester: 3rd

Submitted to Submitted by

Mr. Hilal Ahmad Shah Jayesh

Assistant Professor Reg. No. 221348008

Department of Computer Science and Engineering

Faculty of Engineering and Technology


Table of Content
Course Name: Artificial Intelligence Lab
Course Code: 13480320

S.No Name of Experiments Signature

1. Program to Solve 8 - Queens Problem.

2. Program to implement DFS.


3. Program to implement BFS.
4.

5.

6.
7.
8.

9.
10.
Experiment : 1
Q. Write a program to solve 8 – Queen Problem

Ans.

def is_safe(board, row, col):


# Check the left side of the current row
for i in range(col):

if board[row][i] == 1:
return False
# Check upper diagonal on the left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:

return False
# Check lower diagonal on the left side
for i, j in zip(range(row, len(board)), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_queens(board, col):
if col >= len(board):

return True
for i in range(len(board)):
if is_safe(board, i, col):

board[i][col] = 1
if solve_queens(board, col + 1):
return True
board[i][col] = 0
return False
def print_solution(board):
for row in board:

print(" ".join(["Q" if val == 1 else "-" for val in row]))def


solve_8_queens():
board = [[0 for _ in range(8)] for _ in range(8)]
if solve_queens(board, 0):
print_solution(board)
else:
print("No solution exists.")
solve_8_queens()

OUTPUT:
Experiment : 2
Q. Write a Program to implement DFS.
Ans.

graph = {
'A': ['B', 'C', 'D'],'B': ['E'],'C': ['D', 'E'],'D': ['A', 'C'],'E': ['C', 'B']}
visited = set()
def dfs(visited, graph, root):
if root not in visited:
print(root)

visited.add(root)
for neighbor in graph[root]:
dfs(visited, graph, neighbor)
dfs(visited, graph, 'A')
OUTPUT:
Experiment : 3
Q. Write a Program to implement BFS.
Ans.

import collections
def bfs(graph, root):
visited = set()
queue = collections.deque([root])
while queue:
vertex = queue.popleft()
visited.add(vertex)

for i in graph[vertex]:
if i not in visited:
queue.append(i)

print(visited)

if name == " main ":


# Dictionary representing the graph
graph = {0: [1, 2, 3], 1: [0, 2], 2: [0, 1, 4], 3: [0], 4: [2]}
bfs(graph, 0)
OUTPUT:

You might also like