用python实现马踏棋盘
时间: 2023-09-18 10:16:23 浏览: 57
以下是Python实现马踏棋盘的代码:
```python
def legal_moves(x, y, board):
"""Return a list of legal moves from (x, y) on board."""
moves = []
for dx, dy in ((1, 2), (2, 1), (-1, 2), (-2, 1),
(1, -2), (2, -1), (-1, -2), (-2, -1)):
if 0 <= x + dx < len(board) and 0 <= y + dy < len(board) and \
board[x+dx][y+dy] == -1:
moves.append((x+dx, y+dy))
return moves
def tour(n, path, board, x=0, y=0, count=0):
"""Recursive generator that yields each path that covers all squares."""
# This implementation uses Warnsdorff's heuristic.
board[x][y] = count
path.append((x, y))
count += 1
if count == n**2:
yield path
else:
# Try each legal move from here.
moves = legal_moves(x, y, board)
# sort moves in decreasing order of next move choices
moves.sort(key=lambda m: len(legal_moves(m[0], m[1], board)), reverse=True)
for move in moves:
yield from tour(n, path, board, move[0], move[1], count)
path.pop()
board[x][y] = -1
def print_board(board):
"""Print the board."""
for row in board:
print(' '.join(str(cell).rjust(2) for cell in row))
n = int(input("Enter the size of the board: "))
board = [[-1] * n for _ in range(n)]
path = []
for path in tour(n, path, board):
print_board(board)
print()
print("All tours found.")
```
运行该代码后,程序会要求输入棋盘的大小。然后,程序会输出所有马踏棋盘的路径。