-2
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");  

This is a subsection of my program for NQueens, but I seem to always get: There are 0 solutions to the 8-queens problem. I tried debugging with system.out.prints in the main method, which led me to guess that there would be something wrong in my boolean method, but I don't think it's doing anything wrong. I'm unsure if my while statement is incorrect or if the break inside the while loop is initialized before anything is even done. Thanks for the help and guidance and I'm sorry if my program and explanation makes no sense

4

1 回答 1

1

这就是为什么您立即获得零的原因:

s.push(0);
while(s.size() > n) // n is 8
{
 //...
}
return Solved;

当程序到达时,while 条件s的大小为 1,n为 8。这将立即失败并导致方法返回零。

但这不是算法的唯一问题。你应该认真地重新考虑一下。

于 2014-10-11T19:07:26.893 回答