I am trying to solve the 8 puzzle or sliding tile problem using Hill-Climbing algorithm in python. I Wrote the code to print each intermediate step until goal node is reached but no output is shown by the interpreter. Please review my code and tell me about the errors in the code and solution to them.
Hi there, I am trying to solve the 8 puzzle or sliding tile problem using Hill-Climbing algorithm in python. I Wrote the code to print each intermediate step until goal node is reached but no output is shown by the interpreter. Please tell me about the errors in the code and solution to them.
from copy import deepcopy
class State:
def __init__(self, state, parent):
goal_state = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]
self.parent = parent
self.state = state
self.cost = self.calculate_cost(goal_state)
def calculate_cost(self, goal_state):
cost = 0
for i in range(3):
for j in range(3):
if self.state[i][j] != goal_state[i][j]:
cost += 1
return cost
def generate_neighbors(self):
neighbors = []
for i in range(3):
for j in range(3):
if self.state[i][j] == 0:
if i >= 0 and i != 2: #move down
new_state = deepcopy(self.state)
new_state[i][j], new_state[i+1][j] = new_state[i+1][j], new_state[i][j]
neighbors.append(State(new_state, self))
if i <=2 and i != 0: #move up
new_state = deepcopy(self.state)
new_state[i][j], new_state[i-1][j] = new_state[i-1][j], new_state[i][j]
neighbors.append(State(new_state, self))
if j >= 0 and j != 2: # move right
new_state = deepcopy(self.state)
new_state[i][j], new_state[i][j+1] = new_state[i][j+1], new_state[i][j]
neighbors.append(State(new_state, self))
if j <= 2 and j != 0: # move left
new_state = deepcopy(self.state)
new_state[i][j], new_state[i][j-1] = new_state[i][j-1], new_state[i][j]
neighbors.append(State(new_state, self))
return neighbors
def hill_climbing(initial_state):
current_state = State(initial_state, None)
while current_state.cost > 0:
neighbors = current_state.generate_neighbors()
best_neighbor = min(neighbors, key = lambda state: state.cost)
if current_state.cost > best_neighbor.cost:
current_state = best_neighbor
path = []
while current_state is not None:
path.append(current_state.state)
current_state = current_state.parent
return path[::-1]
initial_state = [[2, 0, 3], [1, 8, 4], [7, 6, 5]]
path = hill_climbing(initial_state)
# Print the solution path
for state in path:
print(state)
Shrey Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.