数字华容道3x3自动复原python
时间: 2023-10-20 20:32:48 浏览: 198
以下是一个简单的数字华容道3x3自动复原Python代码:
```python
import copy
class Node:
def __init__(self, state, g, h, parent=None):
self.state = state
self.g = g
self.h = h
self.parent = parent
def f(self):
return self.g + self.h
def __lt__(self, other):
return self.f() < other.f()
def h(state):
goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
distance = 0
for i in range(3):
for j in range(3):
if state[i][j] == 0:
continue
x, y = divmod(state[i][j] - 1, 3)
distance += abs(x - i) + abs(y - j)
return distance
def get_children(node):
children = []
for i in range(3):
for j in range(3):
if node.state[i][j] == 0:
if i > 0:
new_state = copy.deepcopy(node.state)
new_state[i][j], new_state[i-1][j] = new_state[i-1][j], new_state[i][j]
children.append(Node(new_state, node.g+1, h(new_state), node))
if i < 2:
new_state = copy.deepcopy(node.state)
new_state[i][j], new_state[i+1][j] = new_state[i+1][j], new_state[i][j]
children.append(Node(new_state, node.g+1, h(new_state), node))
if j > 0:
new_state = copy.deepcopy(node.state)
new_state[i][j], new_state[i][j-1] = new_state[i][j-1], new_state[i][j]
children.append(Node(new_state, node.g+1, h(new_state), node))
if j < 2:
new_state = copy.deepcopy(node.state)
new_state[i][j], new_state[i][j+1] = new_state[i][j+1], new_state[i][j]
children.append(Node(new_state, node.g+1, h(new_state), node))
return children
def a_star(start_state):
start_node = Node(start_state, 0, h(start_state))
queue = [start_node]
visited = set()
while queue:
node = queue.pop(0)
if node.state == [[1, 2, 3], [4, 5, 6], [7, 8, 0]]:
path = []
while node:
path.append(node.state)
node = node.parent
path.reverse()
return path
if node.state in visited:
continue
visited.add(node.state)
children = get_children(node)
queue.extend(children)
queue.sort()
return None
start_state = [[2, 8, 3], [1, 6, 4], [7, 0, 5]]
path = a_star(start_state)
for state in path:
for row in state:
print(row)
print()
```
以上代码实现了一个A*算法来解决数字华容道3x3自动复原问题。该算法中使用了一个节点类来存储每个状态的信息,包括状态矩阵、当前已经花费的步数、预估的剩余步数、和父节点。预估的剩余步数使用了曼哈顿距离作为评估函数。在算法实现中使用了一个队列来存储待处理的节点,并按照估价函数f进行排序。该算法的时间复杂度是指数级别的,但实际测试中表现良好。
阅读全文