【发布时间】:2014-10-11 18:28:05
【问题描述】:
public class SomeQueens {
static Stack<Integer> s= new Stack<Integer>();
static int Solved = 0;
static int current = 0;
public static int solve(int n) { // n is 8
while(current < n) { // should I use current < n instead
for (int i = current; i < n; i++) {
if(validPosition(i)) {
s.push(i);
current = 0;
}
}
if(!validPosition(current)) {
if(s.empty()) {
break;
}
if(!s.empty()) {
s.pop();
current++;
}
}
if(s.size() == n) {
s.pop();
current++;
printSolution(s);// this is a method, but it shouldn't matter for this
Solved++;
}
}
return Solved;
}
public static boolean validPosition(int column) {
for( int row = 0; row < s.size(); row++)
if(s.get(row) == column || ((column - s.get(row)) == (s.size() - row)) ||
((s.get(row) - column) == (s.size() - row)) )
return false; // there's a conflict
return true; // no conflict;
}
//it's called by int num = solve(n);
//sop("There're" + num + "sols to the" + n "queens prob");
这是我的 NQueens 程序的一个小节,但我似乎总是得到:8-queens 问题有 0 个解决方案。我尝试在 main 方法中使用 system.out.prints 进行调试,这让我猜测我的布尔方法中会有问题,但我认为它没有做错任何事情。 我不确定我的 while 语句是否不正确,或者 while 循环内的中断是否在任何事情完成之前就被初始化了。感谢您的帮助和指导,如果我的程序和解释没有意义,我很抱歉
【问题讨论】:
-
为什么不使用递归?
-
int solve(int n)似乎没有返回声明。这不应该编译。 -
我不能使用递归,我很抱歉没有放置它——现在我做到了。很抱歉没有澄清事情。
标签: java backtracking n-queens