测试一下这个怎么样
from queue import PriorityQueue
# 定义棋盘的大小
ROWS = 3
COLS = 3
# 定义移动方向
MOVES = [(0, 1), (0, -1), (1, 0), (-1, 0)] # 右、左、下、上
# 定义棋盘类
class Board:
def __init__(self, state, parent=None, g=0, h=0):
self.state = state
self.parent = parent
self.g = g # 实际代价
self.h = h # 启发式函数估计值
# 找到空格位置
def find_empty_pos(self):
for i in range(ROWS):
for j in range(COLS):
if self.state[i][j] == 0:
return (i, j)
# 判断移动是否合法
def is_valid_move(self, move):
new_row = self.empty_pos[0] + move[0]
new_col = self.empty_pos[1] + move[1]
return 0 <= new_row < ROWS and 0 <= new_col < COLS
# 执行移动
def move(self, move):
new_row = self.empty_pos[0] + move[0]
new_col = self.empty_pos[1] + move[1]
new_state = [row[:] for row in self.state]
new_state[self.empty_pos[0]][self.empty_pos[1]] = new_state[new_row][new_col]
new_state[new_row][new_col] = 0
return Board(new_state, parent=self, g=self.g + 1, h=self.manhattan_distance(new_state))
# 计算曼哈顿距离
def manhattan_distance(self, state):
distance = 0
for i in range(ROWS):
for j in range(COLS):
if state[i][j] != 0:
target_row = (state[i][j] - 1) // COLS
target_col = (state[i][j] - 1) % COLS
distance += abs(i - target_row) + abs(j - target_col)
return distance
# 判断是否达到目标状态
def is_goal(self, goal_state):
return self.state == goal_state
# 获取可行的移动
def get_valid_moves(self):
self.empty_pos = self.find_empty_pos()
valid_moves = []
for move in MOVES:
if self.is_valid_move(move):
valid_moves.append(move)
return valid_moves
# 定义优先级队列中的比较函数
def __lt__(self, other):
return self.g + self.h < other.g + other.h
# A*算法
def astar(start_state, goal_state):
start_board = Board(start_state)
goal_board = Board(goal_state)
open_set = PriorityQueue()
open_set.put(start_board)
closed_set = set()
while not open_set.empty():
current_board = open_set.get()
if current_board.is_goal(goal_state):
return current_board
closed_set.add(tuple(map(tuple, current_board.state)))
for move in current_board.get_valid_moves():
next_board = current_board.move(move)
if tuple(map(tuple, next_board.state)) not in closed_set:
open_set.put(next_board)
return None
# 测试
start_state = [
[1, 2, 3],
[0, 4, 6],
[7, 5, 8]
]
goal_state = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 0]
]
goal_board = astar(start_state, goal_state)
if goal_board:
print("Solution found!")
# 输出路径
path = []
while goal_board:
path.append(goal_board.state)
goal_board = goal_board.parent
for state in reversed(path):
print(state)
else:
print("No solution found.")