标题几乎说明了一切。我一直在努力解决这个问题,并且无法找到防止它发生的方法。也许某种方式存储无效的展示位置?或者我如何实现一种方法让它从上一次“恢复”到这一行,这样它不会再次选择相同的值?
忽略while i,它仅用于调试。与印刷品相同。
import java.util.Stack;
public class NQueens {
//***** fill in your code here *****
//feel free to add additional methods as necessary
//finds and prints out all solutions to the n-queens problem
public static int solve(int n) {
//***** fill in your code here *****
//Scaffolding code from Stacks.pdf
//------------------------------------------------------------------------------------------------------------------
// Create empty stack and set current position to 0
Stack<Integer> s = new Stack<Integer>();
int column = 0;
int row = 0;
int solutionsCount = 0;
int i = 0;
//Repeat {
//loop from current position to the last position until a valid position is found //current row
while (i < 5){
for(column = 0; column < n ;column++) {
//if there is a valid position
System.out.println("Top of for loop");
System.out.println("Column/index for = " + column + "; Row is: " + row);
System.out.println("Stack size = " + s.size());
System.out.println();
if (isValid(s, column, row)) {
s.push(column);
//push the position to stack, set current position to 0 // move to next ro
row++;
column = 0;
}//if
}//for
//if there is no valid position
if(!isValid(s, column, row) || column >= n){
//if stack is empty, break // stop search
if(s.size() == 0){
break; //stop search
}//if
//else pop from stack, set current position to next position // backtracking to previous row
else{
s.pop();
column++;
row--;
}//else
}//if
//if stack has size N { // a solution is found
if (s.size() == n){
solutionsCount++;
printSolution(s);
//pop from stack, set current position to next position // backtracking to find next solution
s.pop();
row--;
column++;
}//if
else {
}//else
i++;
// Make sure to change this when not bug testing for 4x4
}//end for loop
//update the following statement to return the number of solutions found
return solutionsCount;
}//solve()
答案 0 :(得分:0)
这看起来像是家庭作业,所以这里有一些指示:
column
循环后修改for
变量。显然,您希望其值继续进入while
的下一次迭代。但是,当while
再次启动时,您要做的第一件事就是将column
设置为0
for (column = 0; ....)
,这会覆盖其值。 column
从while
的一次迭代到下一次迭代应该包含哪些信息?column
循环中将0
设置为for
,但在下一个1
之前,column++
将for
增加到column
迭代。 if
语句中使用for
。在for
循环完成之后,您期望该变量的值是多少? if
循环之后,您有两个for
语句尝试检查相同的条件 - if
循环是否找到了解决方案。只有第二个if
更加清晰。你甚至需要两个column
s?order: sequelize.fn('field', sequelize.col('type'), 'source', 'translated')
值放入堆栈,但是当您将它们从堆栈中弹出时,您只需丢弃它们。你对这些价值观有什么用处吗?