我正在尝试使用Python中的爬山算法解决8谜题或滑动瓷砖问题。我编写了代码来打印每个中间步骤,直到到达目标节点,但解释器没有显示任何输出。请检查我的代码并告诉我代码中的错误和解决方案。
您好,我正在尝试使用 python 中的爬山算法解决 8 拼图或滑动瓷砖问题。我编写了代码来打印每个中间步骤,直到到达目标节点,但解释器没有显示任何输出。请告诉我代码中的错误以及解决方案。
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)
我不确定,但也许问题是由
if
函数中的 generate_neighbors
语句引起的。
尝试改变:
if self.state[i][j] == 0
至 if self.state[i][j] != 0