Professional Documents
Culture Documents
Arpit Ai
Arpit Ai
(18B17CI475)
LAB RECORD
Submitted by
ARPIT AWASTHI [221B086]
2023-2024
INDEX
Exp. ExperimentTitleStart End Signatur
No. Date Date e
def solve_queens_util(board,col):
if col>=N:
return True
for i in range(N):
if is_safe(board,i,col):
board[i][col]=1
if solve_queens_util(board,col+1):
return True
board[i][col]=0
return False
def solve_queens(n):
global N
N=n
board=[[0 for _ in range(N)]for _ in range(N)]
if not solve_queens_util(board,0):
def print_board(board):
for i in range(N):
for j in range(N):
print(board[i][j],end=" ")
print()
if __name__=="__main__":
solve_queens(4)
print("\n")
solve_queens(8)
def is_safe(self,node,color):
for neighbor in self.graph[node]:
if self.colors[neighbor]==color:
return False
return True
def solve(self,node):
if node==self.num_nodes:
return True
for color in range(1,5):
if self.is_safe(node,color):
self.colors[node]=color if
self.solve(node+1): return True
self.colors[node]=0 return
False
def color_map(self):
if self.solve(0):
color_map={}
for i in range(self.num_nodes):
color_map[i]=self.colors[i] return
color_map
else:
return "No solution exists."
if __name__=="__main__":
graph={
0:[1,2,3],
1:[0,2],
2:[0,1,3],
3:[0,2]
}
map_coloring=MapColoring(graph)
result=map_coloring.color_map()
print("Coloring of the map:")
print(result)
def __lt__(self,other):
return(self.cost+self.depth)<(other.cost+other.depth)
def __eq__(self,other):
return self.state==other.state
def __hash__(self):
return hash(str(self.state))
def expand(self):
children=[]
for action in self.actions():
next_state=self.result(action)
if next_state:
children.append(PuzzleNode(next_state,self,action,self.cost+1)) return
children
def actions(self):
actions=[]
i,j=self.find_blank()
if i>0:
actions.append('up')
if i<2:
actions.append('down')
if j>0:
actions.append('left')
if j<2:
actions.append('right')
return actions
def result(self, action):
i,j=self.find_blank()
new_state=[row[:] for row in self.state]
if action=='up':
new_state[i][j],new_state[i-1][j]=new_state[i-1][j],new_state[i][j] elif
action=='down':
new_state[i][j],new_state[i+1][j]=new_state[i+1][j],new_state[i][j] elif
action=='left':
new_state[i][j],new_state[i][j+1]=new_state[i][j+1],new_state[i][j] else:
return None
return new_state
def find_blank(self):
for i in range(3):
for j in range(3):
if self.state[i][j]==0:
return i,j
return None
def print_path(self):
path=[]
node=self
while node:
path.append(node.state)
node=node.parent
path.reverse()
for state in path:
print_state(state)
print()
def print_state(state):
for row in state:
print(row)
print()
def manhattan_distance(state):
distance=0
for i in range(3):
for j in range(3):
if state[i][j]!=0:
x,y=divmod(state[i][j]-1,3)
distance+=abs(x-i)+abs(y-j) return
distance
def solve_puzzle(initial_state):
initial_node=PuzzleNode(initial_state)
frontier=[initial_node]
visited=set()
heapq.heapify(frontier)
while frontier:
node=heapq.heappop(frontier) if
node.state==goal_state:
return node
visited.add(node)
for child in node.expand(): if
child not in visited:
heapq.heappush(frontier,child) return
None
initial_state=[[1,2,3],
[4,5,6],
[7,8,0]]
goal_state=[[1,2,3],
[4,5,6],
[7,8,0]]
solution_node=solve_puzzle(initial_state
) if solution_node:
print("Solution found:")
solution_node.print_path()
else:
print("No solution found.")
Problem 5: Solve “Latin Square” problem.
def is_safe(square,row,col,num):
if num in square[row]:
return False
for i in range(len(square)):
if square[i][col]==num:
return False
return True
def
solve_latin_square(square,n,row=0,col=0): if
row==n:
return True
if col==n:
return solve_latin_square(square,n,row+1,0) if
square[row][col]!=0:
if is_safe(square,row,col,num):
square[row][col]=num
if solve_latin_square(square,n,row,col+1):
return True
square[row][col]=0
return False
def print_square(square):
for row in square:
print(" ".join(map(str,row)))
def latin_square(n):
square=[[0]*n for _ in range(n)]
if solve_latin_square(square,n):
print("Latin Square Solution:")
print_square(square)
else:
print("No solution exists for the given size.")
n=4
latin_square(n)
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 tic_tac_toe():
board=[[' ' for _ in range(3)]for _ in range(3)]
player='X'
while True:
print_board(board)
row=int(input("Enter row (0,1,or 2): "))
col=int(input("Enter column (0,1,or 2): ")) if
board[row][col]==' ':
board[row][col]=player
winner=check_winner(board)
if winner:
print_board(board)
print(f"Player {winner} wins!")
break
elif all(all(cell!=' ' for cell in row)for row in board):
print_board(board)
print("It's a draw!")
break
else:
player='O' if player=='X' else 'X' else:
print("That cell is already occupied. Try again.")
if __name__=="__main__":
tic_tac_toe()
def print_board(self):
for row in self.board:
print(" | ".join(row))
print("-"*29)
def is_valid_move(self,start,end):
x1,y1=start
x2,y2=end
if self.board[x2][y2]!=" ":
return False
if self.board[x1][y1]=="X":
if x2-x1==1 and abs(y2-y1)==1:
return True
elif x2-x1==2 and abs(y2-y1)==2: if
self.board[(x1+x2)//2][(y1+y2)//2]=="O": return
True
elif self.board[x1][y1]=="O":
if x1-x2==1 and abs(y2-y1)==1:
return True
elif x1-x2==2 and abs(y2-y1)==2: if
self.board[(x1+x2)//2][(y1+y2)//2]=="X": return
True
return False
def make_move(self,start,end):
x1,y1=start
x2,y2=end
self.board[x2][y2]=self.board[x1][y1]
self.board[x1][y1]=" "
if abs(x2-x1)==2:
self.board[(x1+x2)//2][(y1+y2)//2]=" "
def switch_player(self):
self.current_player="O" if self.current_player=="X" else "X"
def play(self):
while True:
self.print_board()
print(f"Player {self.current_player}'s turn")
start=tuple(map(int, input("Enter start position (row, column): ").split(",")))
end=tuple(map(int, input("Enter end position (row, column): ").split(","))) if
self.is_valid_move(start,end):
self.make_move(start,end)
self.switch_player()
else:
print("Invalid move, try again.")
if self.check_winner():
print(f"Player {self.current_player} wins!")
break
def check_winner(self):
for row in self.board:
if "X" in row and "O" not in row:
return True
if "O" in row and "X" not in row:
return True
return False
if __name__ == "__main__":
game=Checkers()
game.play()