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

Aiandmlextra Programs

AI and ML subject programs about DFS

Uploaded by

dhivya sri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views12 pages

Aiandmlextra Programs

AI and ML subject programs about DFS

Uploaded by

dhivya sri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

TIC TOE (DFS)


PROGRAM: (program name TICTOE.py in VS)
import math

def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)

def check_winner(board):
for row in board:
if row[0] == row[1] == row[2] != ' ':
return row[0]
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] != ' ':
return board[0][col]

if board[0][0] == board[1][1] == board[2][2] != ' ':


return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != ' ':
return board[0][2]

return None

def check_draw(board):
for row in board:
if ' ' in row:
return False
return True

def minimax(board, depth, is_maximizing):


winner = check_winner(board)
if winner == 'X':
return -1
if winner == 'O':
return 1
if check_draw(board):
return 0

if is_maximizing:
best_score = -math.inf
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
score = minimax(board, depth + 1, False)
board[i][j] = ' '
best_score = max(score, best_score)
return best_score
else:
best_score = math.inf
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
score = minimax(board, depth + 1, True)
board[i][j] = ' '
best_score = min(score, best_score)
return best_score

def find_best_move(board):
best_score = -math.inf
move = None
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
score = minimax(board, 0, False)
board[i][j] = ' '
if score > best_score:
best_score = score
move = (i, j)
return move

def get_valid_input():
while True:
try:
row, col = map(int, input("Enter row and column (0, 1, 2): ").split())
if row in range(3) and col in range(3):
return row, col
else:
print("Invalid input. Please enter numbers between 0 and 2.")
except ValueError:
print("Invalid input. Please enter two numbers separated by a space.")

def tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'

while True:
print_board(board)
if current_player == 'X':
print(f"Player {current_player}'s turn")
row, col = get_valid_input()
if board[row][col] != ' ':
print("Cell already taken. Try again.")
continue
board[row][col] = 'X'
else:
print(f"Player {current_player}'s turn (AI)")
move = find_best_move(board)
if move:
board[move[0]][move[1]] = 'O'

winner = check_winner(board)
if winner:
print_board(board)
print(f"Player {winner} wins!")
break

if check_draw(board):
print_board(board)
print("The game is a draw!")
break

current_player = 'O' if current_player == 'X' else 'X'

if __name__ == "__main__":
tic_tac_toe()
OUTPUT:
| |
-----
| |
-----
| |
-----
Player X's turn
Enter row and column (0, 1, 2): 0 0
X| |
-----
| |
-----
| |
-----
Player O's turn (AI)
X| |
-----
|O|
-----
| |
-----
Player X's turn
Enter row and column (0, 1, 2): 1 0
X| |
-----
X|O|
-----
| |
-----
Player O's turn (AI)
X| |
-----
X|O|
-----
O| |
-----
Player X's turn
Enter row and column (0, 1, 2): 0 2
X| |X
-----
X|O|
-----
O| |
-----
Player O's turn (AI)
X|O|X
-----
X|O|
-----
O| |
-----
Player X's turn
Enter row and column (0, 1, 2): 2 1
X|O|X
-----
X|O|
-----
O|X|
-----
Player O's turn (AI)
X|O|X
-----
X|O|O
-----
O|X|
-----
Player X's turn
Enter row and column (0, 1, 2): 2 2
X|O|X
-----
X|O|O
-----
O|X|X
-----
The game is a draw!

2. WATER JUG(DFS)
PROGRAM: (program name WATER_JUG.py in VS)
from collections import defaultdict

def waterJugSolver(jug1, jug2, aim, amt1=0, amt2=0, visited=None):

if visited is None:

visited = defaultdict(lambda: False)

# Checks for our goal and returns true if achieved.

if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):

print(f"({amt1}, {amt2})")

return True

# Checks if we have already visited the combination or not. If not, then it proceeds further.

if not visited[(amt1, amt2)]:

print(f"({amt1}, {amt2})")

# Mark this state as visited

visited[(amt1, amt2)] = True


# Check for all the 6 possibilities and see if a solution is found in any one of them.

return (waterJugSolver(jug1, jug2, aim, 0, amt2, visited) or

waterJugSolver(jug1, jug2, aim, amt1, 0, visited) or

waterJugSolver(jug1, jug2, aim, jug1, amt2, visited) or

waterJugSolver(jug1, jug2, aim, amt1, jug2, visited) or

waterJugSolver(jug1, jug2, aim, amt1 + min(amt2, (jug1 - amt1)),

amt2 - min(amt2, (jug1 - amt1)), visited) or

waterJugSolver(jug1, jug2, aim, amt1 - min(amt1, (jug2 - amt2)),

amt2 + min(amt1, (jug2 - amt2)), visited))

# Return False if the combination is already visited to avoid repetition otherwise

# recursion will enter an infinite loop.

return False

if __name__ == "__main__":

# Taking input from the user

jug1 = int(input("Enter the capacity of jug 1: "))

jug2 = int(input("Enter the capacity of jug 2: "))

aim = int(input("Enter the target amount: "))

print("Steps: ")

if not waterJugSolver(jug1, jug2, aim):

print("No solution found.")

OUTPUT:
Enter the capacity of jug 1: 3

Enter the capacity of jug 2: 5

Enter the target amount: 4

Steps:

(0, 0)

(3, 0)

(3, 5)

(0, 5)

(3, 2)

(0, 2)

(2, 0)
(2, 5)

(3, 4)

(0, 4)

3. 8 QUEENS PUZZLE

PROGRAM: (Program name: 8_QUEENS in VS)


def is_safe(board, row, col):

# Check if there is a queen in the same column

for i in range(row):

if board[i][col] == 1:

return False

# Check upper diagonal on left side

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

if board[i][j] == 1:

return False

# Check upper diagonal on right side

for i, j in zip(range(row, -1, -1), range(col, len(board))):

if board[i][j] == 1:

return False

return True

def solve_queens(board, row):

if row >= len(board):

return True

for col in range(len(board)):

if is_safe(board, row, col):

board[row][col] = 1

if solve_queens(board, row + 1):

return True

board[row][col] = 0
return False

def print_board(board):

for row in board:

print(" ".join(map(str, row)))

def solve_8_queens():

board = [[0] * 8 for _ in range(8)]

if solve_queens(board, 0):

print("Solution found:")

print_board(board)

else:

print("No solution found")

if __name__ == "__main__":

solve_8_queens()

OUTPUT:
Solution found:

10000000

00001000

00000001

00000100

00100000

00000010

01000000

00010000

DFS IN TREE
PROGRAM: ( Program name: DFS_TREE in VS )
class TreeNode:

def __init__(self, value):

self.value = value

self.children = []
def add_child(self, child):

self.children.append(child)

def dfs(node):

if node is None:

return

print(node.value)

for child in node.children:

dfs(child)

def build_tree():

root_value = input("Enter the value of the root node: ")

root = TreeNode(root_value)

num_children = int(input(f"Enter the number of children for {root_value}: "))

for _ in range(num_children):

child_value = input(f"Enter the value of child node: ")

child = TreeNode(child_value)

root.add_child(child)

for child in root.children:

build_subtree(child)

return root

def build_subtree(parent):

num_children = int(input(f"Enter the number of children for {parent.value}: "))

for _ in range(num_children):

child_value = input(f"Enter the value of child node: ")

child = TreeNode(child_value)

parent.add_child(child)

build_subtree(child)

if __name__ == "__main__":

root = build_tree()

print("\nDFS Traversal:")
dfs(root)

OUTPUT:

THE STRUCTURE OF TREE USED IN OUTPUT:

/ | \

B C D

/ \ |

E F G

Enter the value of the root node: a

Enter the number of children for a: 3

Enter the value of child node: b

Enter the value of child node: c

Enter the value of child node: d

Enter the number of children for b: 2

Enter the value of child node: e

Enter the number of children for e: 0

Enter the value of child node: f

Enter the number of children for f: 0

Enter the number of children for c: 0

Enter the number of children for d: 1

Enter the value of child node: g

Enter the number of children for g: 0

DFS Traversal:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy