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);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值