我正在尝试编写一个有nxn板的程序(用于家庭作业),我需要算法找到所有可能的解决方案,让n个皇后处于一个位置,其中没有一个皇后可以捕获每个其他。所以我现在的代码看起来像这样。
import java.util.Stack;
public class NQueens {
public static int solve(int n) {
Stack<Integer> s = new Stack<Integer>();
int current = 0;
int numSolutions = 0;
while(!(current>n)){
if(s.size() == n){
break;
}
if(current == n){
if((s.peek()==n) && (s.size() == 1)){
break;
}
if(s.peek() == n){
s.pop();
current = s.pop()+1;
}
else{
current = s.pop()+1;
}
}
else if(validPositionChecker(s, current)){
s.push(current);
current = 0;
}
else{
current++;
}
}
if(s.size()==n){
printSolution(s);
numSolutions++
}
return numSolutions;
}
public static boolean validPositionChecker(Stack<Integer> s, int currentPosition) {
for (int i = 0; i < s.size(); i++) {
if (s.get(i) == currentPosition){
return false;
}
if ((s.get(i) - currentPosition) == (s.size() - i)){
return false;
}
if ((currentPosition - s.get(i)) == (s.size() - i)){
return false;
}
}
return true;
}
//this method prints out a solution from the current stack
private static void printSolution(Stack<Integer> s) {
for (int i = 0; i < s.size(); i ++) {
for (int j = 0; j < s.size(); j ++) {
if (j == s.get(i))
System.out.print("Q ");
else
System.out.print("* ");
}
System.out.println();
}
System.out.println();
}//printSolution()
public static void main(String[] args) {
int n = 8;
// pass in parameter n from command line
if (args.length == 1) {
n = Integer.parseInt(args[0].trim());
if (n < 1) {
System.out.println("Incorrect parameter");
System.exit(-1);
}//if
}//if
int number = solve(n);
System.out.println("There are " + number + " solutions to the " + n + "-queens problem.");
}//main()
}
所以解释这段代码。这段代码有效。但它只打印出其中一个解决方案。在8x8的默认nxn板中,它应该有92个独特的解决方案。
我的问题是如何让它打印所有解决方案。我理解我可以在我的给定while循环中使用另一个在solve方法中,但我不知道什么参数给它的while循环退出。基本上要重申一下,我需要知道在什么条件下我知道什么时候更大的while循环会在找到所有解决方案时停止。
我必须使用堆栈,我不能使用递归来完成这项功课。递归会使它变得更简单。
答案 0 :(得分:0)
import java.util.Stack;
public class QueenSolver {
private static final int NUM_QUEENS = 8;
private static int[] board = new int[NUM_QUEENS];
public static void solve(int n) {
int current = 0;
int numSolutions = 0;
Stack<Integer> s = new Stack<>();
while (true) {
while (current < n) {
if (isBoardCorrect(s, current)) {
s.push(current);
board[s.size() - 1] = current;
current = 0;
} else {
current++;
}
}
if (s.size() == n) {
printSolution(++numSolutions);
}
if (s.isEmpty()) {
break;
}
if (s.peek() == n) {
s.pop();
}
current = s.pop() + 1;
}
}
private static boolean isBoardCorrect(Stack<Integer> s, int currentPosition) {
for (int i = 0; i < s.size(); i++) {
if (board[i] == currentPosition
|| currentPosition == board[i]
|| Math.abs(currentPosition - board[i]) == s.size() - i) {
return false;
}
}
return true;
}
private static void printSolution(int num) {
System.out.print(num + ": ");
for (int i = 0; i < board.length; i++) {
System.out.print("(" + i + "," + board[i] + ")");
if (i < board.length - 1) {
System.out.print(", ");
}
}
System.out.println();
}
public static void main(String[] args) {
QueenSolver.solve(8);
}
}