python实现A算法8数码
时间: 2023-06-16 09:08:15 浏览: 134
A*算法是一种启发式搜索算法,可以用于解决8数码问题。下面是python实现A*算法8数码的代码:
```
import heapq
class Board:
def __init__(self, start_state, goal_state):
self.start_state = start_state
self.goal_state = goal_state
self.blank_idx = start_state.index(0)
self.goal_idx = None
self.calc_goal_idx()
self.g = 0
self.h = self.heuristic()
self.f = self.g + self.h
def calc_goal_idx(self):
for i in range(9):
if self.goal_state[i] != self.start_state[i]:
self.goal_idx = self.goal_state.index(self.start_state[i])
break
def heuristic(self):
manhattan = 0
for i in range(9):
if self.start_state[i] != 0:
manhattan += abs(i // 3 - self.goal_idx // 3) + abs(i % 3 - self.goal_idx % 3)
return manhattan
def move_blank(self, idx):
new_state = self.start_state.copy()
new_state[self.blank_idx], new_state[idx] = new_state[idx], new_state[self.blank_idx]
return Board(new_state, self.goal_state)
def __lt__(self, other):
return self.f < other.f
def a_star(start_state, goal_state):
open_list = []
closed_list = set()
start_board = Board(start_state, goal_state)
heapq.heappush(open_list, start_board)
while open_list:
cur_board = heapq.heappop(open_list)
if cur_board.start_state == goal_state:
return cur_board.g
closed_list.add(tuple(cur_board.start_state))
for move_idx in [-3, 3, -1, 1]:
if cur_board.blank_idx % 3 == 0 and move_idx == -1:
continue
if cur_board.blank_idx % 3 == 2 and move_idx == 1:
continue
new_blank_idx = cur_board.blank_idx + move_idx
if new_blank_idx < 0 or new_blank_idx >= 9:
continue
if abs(move_idx) == 3:
if move_idx < 0:
new_board = cur_board.move_blank(cur_board.blank_idx - 3)
else:
new_board = cur_board.move_blank(cur_board.blank_idx + 3)
else:
new_board = cur_board.move_blank(new_blank_idx)
if tuple(new_board.start_state) in closed_list:
continue
new_board.g = cur_board.g + 1
new_board.h = new_board.heuristic()
new_board.f = new_board.g + new_board.h
heapq.heappush(open_list, new_board)
return -1
if __name__ == '__main__':
start_state = [1, 2, 3, 4, 5, 6, 0, 7, 8]
goal_state = [0, 1, 2, 3, 4, 5, 6, 7, 8]
moves = a_star(start_state, goal_state)
print("Minimum number of moves required:", moves)
```
此代码实现了A*算法解决8数码问题。输入开始状态和目标状态,输出移动最少的步数。
阅读全文