华容道程序代码
时间: 2023-09-03 12:12:56 浏览: 97
华容道是一种经典的益智游戏,下面是一个基于 Python 的华容道程序代码示例:
```python
import copy
# 棋盘类
class Board:
def __init__(self, board):
self.width = len(board[0])
self.height = len(board)
self.board = board
# 返回空格坐标
def get_blank(self):
for i in range(self.height):
for j in range(self.width):
if self.board[i][j] == 0:
return (i, j)
# 移动棋子
def move(self, direction):
i, j = self.get_blank()
if direction == 'up' and i > 0:
self.board[i][j], self.board[i-1][j] = self.board[i-1][j], self.board[i][j]
elif direction == 'down' and i < self.height-1:
self.board[i][j], self.board[i+1][j] = self.board[i+1][j], self.board[i][j]
elif direction == 'left' and j > 0:
self.board[i][j], self.board[i][j-1] = self.board[i][j-1], self.board[i][j]
elif direction == 'right' and j < self.width-1:
self.board[i][j], self.board[i][j+1] = self.board[i][j+1], self.board[i][j]
# 判断是否完成
def is_solved(self):
num = 0
for i in range(self.height):
for j in range(self.width):
if self.board[i][j] != num:
return False
num += 1
return True
# 搜索类
class Search:
def __init__(self, board):
self.board = board
self.path = []
# 深度优先搜索
def dfs(self, depth):
if depth == 0:
if self.board.is_solved():
return True
else:
return False
for direction in ['up', 'down', 'left', 'right']:
new_board = copy.deepcopy(self.board)
new_board.move(direction)
if (new_board.board not in self.path) and (new_board.board != self.board.board):
self.path.append(new_board.board)
if self.dfs(depth-1):
return True
else:
self.path.pop()
return False
# 迭代加深搜索
def ids(self):
for depth in range(1, 100):
self.path = [self.board.board]
if self.dfs(depth):
return True
return False
# 测试
board = Board([[1, 2, 3], [4, 0, 5], [6, 7, 8]])
search = Search(board)
if search.ids():
for b in search.path:
for row in b:
print(row)
print()
else:
print('No solution')
```
这个程序实现了一个基本的华容道游戏盘面求解,可以通过深度优先搜索和迭代加深搜索实现。
阅读全文