I am trying to solve sliding-tile problem using Hill climbing algorithm in python where in I want to print the each intermediate step but my code isn’t showing any output. I don’t think so that any infinite loop is present in my code. Please review my code and suggest me any solution to it.
from copy import deepcopy
class State:
def init(self, state, parent):
self.parent = parent
self.state = state
def is_goal(self):
return self.state == [[1, 2, 3], [8, 0, 4], [7, 6, 5]]
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 heuristic(state):
goal_state = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]
cost = 0
for i in range(3):
for j in range(3):
if state.state[i][j] != goal_state[i][j]:
cost += 1
return cost
def hill_climbing(initial_state, heuristic):
current_state = initial_state
while not current_state.is_goal():
neighbors = current_state.generate_neighbors()
best_neighbor = neighbors[0]
for neighbor in neighbors:
if heuristic(neighbor) < heuristic(best_neighbor):
best_neighbor = neighbor
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 = State([[2, 0, 3], [1, 8, 4], [7, 6, 5]], None)
path = hill_climbing(initial_state, heuristic)
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.