Ai Lab Assignment-1

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

AI LAB ASSIGNMENT-1

2020-BCS-042

JUPALLI VARSHITHA RAO


Solving 8-Puzzle Using Breadth First Search Algorithm

class State:

def __init__(slf, state, lvl=0):

slf.state = state

slf.lvl = lvl

def calculate_moves(slf):

row, col = slf.find_empty_cell()

res_list = []

if row != 0:

res_list.append(slf.swap(row, col, row - 1, col))

if row != 2:

res_list.append(slf.swap(row, col, row + 1, col))

if col != 0:

res_list.append(slf.swap(row, col, row, col - 1))

if col != 2:

res_list.append(slf.swap(row, col, row, col + 1))

return res_list

def find_empty_cell(slf):

for row in range(3):

for col in range(3):

if slf.state[row][col] == 0:

return row, col

def swap(slf, initial_row, initial_col, final_row, final_col):

temp_arr = copy.deepcopy(slf.state)

temp = temp_arr[initial_row][initial_col]

temp_arr[initial_row][initial_col] = temp_arr[final_row][final_col]
temp_arr[final_row][final_col] = temp

return temp_arr

def cost(arr, goal, lvl):

cost = 0

cost += lvl

for row in range(3):

for col in range(3):

if arr[row][col] != goal[row][col]:

cost += 1

return cost

def solve(initial, goal):

root = State(initial, lvl=0)

count = 0

states = [root]

while len(states) != 0:

current_node = states.pop()

children = current_node.calculate_moves()

costs = []

for child in children:

costs.append(cost(child, goal, current_node.lvl + 1))

min_cost_index = costs.index(min(costs))

print(f"Step: {count+1}")

count += 1

for row in children[min_cost_index]:

print(row)

if children[min_cost_index] == goal:

print("Goal state reached")

else:
states.append(

State(children[min_cost_index], current_node.lvl + 1))

print("Enter initial state: ")

initial_state = []

for i in range(3):

initial_state.append(list(map(int, input().split())))

print("Enter final state:")

goal_state = []

for i in range(3):

goal_state.append(list(map(int, input().split())))

solve(initial_state, goal_state)

You might also like