0% found this document useful (0 votes)
40 views12 pages

AI 1,2,3 Record Programs

The document outlines the implementation of three algorithms: Breadth First Search (BFS), Depth First Search (DFS), and a Tic-Tac-Toe game using Python. BFS explores nodes level by level, while DFS explores as far as possible along each branch before backtracking. The Tic-Tac-Toe game is played on a 3x3 grid where players take turns to mark their spots, aiming to get three in a row.
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)
40 views12 pages

AI 1,2,3 Record Programs

The document outlines the implementation of three algorithms: Breadth First Search (BFS), Depth First Search (DFS), and a Tic-Tac-Toe game using Python. BFS explores nodes level by level, while DFS explores as far as possible along each branch before backtracking. The Tic-Tac-Toe game is played on a 3x3 grid where players take turns to mark their spots, aiming to get three in a row.
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

WEEK-1

AIM: Implement Breadth First Search

What is BFS:

The breadth-first search (BFS) algorithm is used to search a tree or graph data structure for a node that
meets a set of criteria. It starts at the tree’s root or graph and searches/visits all nodes at the current
depth level before moving on to the nodes at the next depth level. Breadth-first search can be used to
solve many problems in graph theory.

Example BFS Algorithm


Step 1)

You have a graph of seven numbers ranging from 0 – 6.

Step 2)

0 or zero has been marked as a root node.


Step 3)

0 is visited, marked, and inserted into the queue data structure.

Step 4)

Remaining 0 adjacent and unvisited nodes are visited, marked, and inserted into the queue.
Step 5)

Traversing iterations are repeated until all nodes are visited.

Program:

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')

Output:
Following is the Breadth-First Search
5 3 7 2 4 8
WEEK-2

AIM: Implement Depth First Search using Python.

What is DFS:
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The
algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph)
and explores as far as possible along each branch before backtracking. Extra memory, usually a stack,
is needed to keep track of the nodes discovered so far along a specified branch which helps in
backtracking of the graph.

Example:

Let's see how the Depth First Search algorithm works with an example. We use an undirected graph

with 5 vertices.

Undirected graph with 5 vertices

We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its

adjacent vertices in the stack.

Visit the element and put it in the visited list

Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already

been visited, we visit 2 instead.


Visit the element at the top of stack

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed

the Depth First Traversal of the graph.


After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed
the Depth First Traversal of the graph.

Program:

# Using a Python dictionary to act as an adjacency list


graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')

Output:

Following is the Depth-First Search:


5 3 2 4 8 7
WEEK-3

AIM: Implement Tic-Tac-Toe game using Python.

What is Tic-Tac-Toe game:

1. The game is played on a grid that's 3 squares by 3 squares.


2.You are X, your friend (or the computer in this case) is O. Players take turns putting their
marks in empty squares.
3.The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the
winner.
4.When all 9 squares are full, the game is over.

Example:

Program:

# Tic-Tac-Toe Program using


# random number in Python
# importing all necessary libraries
import numpy as np
import random
from time import sleep
# Creates an empty board
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
# Check for empty places on board
def possibilities(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
# Select a random place for the player
def random_place(board, player):
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)
# Checks whether the player has three
# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
# Checks whether the player has three
# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
win = True
y=0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win
# Evaluates whether there is
# a winner or a tie
def evaluate(board):
winner = 0
for player in [1, 2]:
if (row_win(board, player) or
col_win(board, player) or
diag_win(board, player)):
winner = player
if np.all(board != 0) and winner == 0:
winner = -1
return winner
# Main function to start the game
def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)
while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
# Driver Code
print("Winner is: " + str(play_game()))
Output:

[[0 0 0]
[0 0 0]
[0 0 0]]
Board after 1 move
[[0 0 0]
[0 0 0]
[1 0 0]]
Board after 2 move
[[0 0 0]
[0 2 0]
[1 0 0]]
Board after 3 move
[[0 1 0]
[0 2 0]
[1 0 0]]
Board after 4 move
[[0 1 0]
[2 2 0]
[1 0 0]]
Board after 5 move
[[1 1 0]
[2 2 0]
[1 0 0]]
Board after 6 move
[[1 1 0]
[2 2 0]
[1 2 0]]
Board after 7 move
[[1 1 0]
[2 2 0]
[1 2 1]]
Board after 8 move
[[1 1 0]
[2 2 2]
[1 2 1]]
Winner is: 2

You might also like