N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
[img]http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png[/img]
Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

N皇后的问题,典型的用回溯法解决的NP问题,用循环递归来处理。从第0行开始,我们创建一个长度为n的数组colInRow[],数组的下标代表行,数组中的元素代表对应行中皇后在列上的位置,例如colInRow[2] = 3, 代表第2行第三列的位置有皇后。每一次递归我们都将一个皇后放在对应行中的某一列中,如果递归到了第n行,我们就将这个结果放入结果集中。在往前寻找的时候,我们要判断加入皇后的位置是否合法,也就是在同一行同一列还有斜对角线上只能有一个皇后,同一行上肯定有只有一个皇后,因为我们递归每一行时,只加一个皇后,如果合法就递归下一行,所以我们只需要检查同一列和同一斜对角线上是否合法。对于同一列上,我们只需要比较当前行之前的行中在这一列是否有皇后即可;对于斜对角线上,符合一个规律|colInRow[i] - colInRow[row] |== row - i , 其中i < row, 满足这个条件都在一个对角线上。代码如下:

public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<List<String>>();
int[] colInRow = new int[n];
solveNQueens(0, n, colInRow, result);
return result;
}
private void solveNQueens(int row, int n, int[] colInRow, List<List<String>> result) {
if(row == n) {
printBoard(n, colInRow, result);
return;
} else {
for(int i = 0; i < n; i++) {
colInRow[row] = i;
if(isValid(row, colInRow)) {
solveNQueens(row + 1, n, colInRow, result);
}
}
}
}
private boolean isValid(int row, int[] colInRow) {
for(int i = 0; i < row; i++) {
if(colInRow[i] == colInRow[row] || Math.abs(colInRow[i] - colInRow[row]) == row - i)
return false;
}
return true;
}

private void printBoard(int n, int[] colInRow, List<List<String>> result) {
List<String> list = new ArrayList<String>();
for(int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
for(int j = 0; j < n; j++) {
if(j == colInRow[i])
sb.append("Q");
else
sb.append(".");
}
list.add(sb.toString());
}
result.add(list);
}
}
N-Queens问题是一个经典的回溯算法问题,它涉及在一个n×n的棋盘上放置n个皇后,使得任意两个皇后都不在同一行、同一列或对角线上。要将其动画演示,你可以使用Python的pygame库来创建一个动态棋盘,并逐步添加皇后的位置。下面是一个简单的示例代码框架: ```python import pygame import numpy as np # 初始化Pygame pygame.init() # 定义棋盘大小和颜色 board_size = (400, 400) cell_size = board_size[0] // n colors = [(255, 255, 255), (0, 0, 0)] # 白色背景,黑色格子 # 创建窗口 screen = pygame.display.set_mode(board_size) pygame.display.set_caption("N-Queens 动画") # 定义函数用于放置皇后并更新图像 def place_queen(position): # ... (在这里实现绘制皇后和删除旧位置的代码) # 主函数 def animate_queens(n): board = np.zeros((n, n), dtype=np.bool) for i in range(n): # 递归尝试每个位置 if not solve_n_queens(i, board): break # 更新屏幕 screen.fill(colors[0]) for j, queen in enumerate(board): if queen: x, y = i * cell_size, j * cell_size draw_square(x, y, colors[1], cell_size) pygame.display.flip() # 短暂暂停以显示动画 pygame.time.wait(500) def solve_n_queens(row, board): # ... (在这里实现N-Queens问题的回溯算法) # 其他辅助函数 def draw_square(x, y, color, size): pygame.draw.rect(screen, color, (x, y, size, size)) # 主程序开始 n = 8 # 可以调整这个值 animate_queens(n) # 循环直到用户关闭窗口 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 清理并退出 pygame.quit() ``` 这个代码示例仅提供了一个基本框架,你需要填充`solve_n_queens()`函数实现回溯算法,以及`place_queen()`函数用于在屏幕上绘制皇后。同时,为了完整实现动画效果,你还需要处理键盘事件或者按钮点击来控制下一个皇后的位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值