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

これは NQueens のための私のプログラムのサブセクションですが、私は常に得ているようです: 8-queens 問題の解決策はありません。main メソッドで system.out.prints を使用してデバッグを試みたところ、ブール値のメソッドに何か問題があるのではないかと推測されましたが、何も問題はないと思います。while ステートメントが間違っているのか、何かが実行される前に while ループ内のブレークが初期化されているのかどうかはわかりません。ヘルプとガイダンスに感謝します。プログラムと説明が意味をなさない場合は申し訳ありません

4

1 に答える 1

1

すぐにゼロになる理由は次のとおりです。

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

プログラムが while 条件に到達するとs、サイズは 1 でn8 になります。これは即座に失敗し、メソッドはゼロを返します。

しかし、アルゴリズムの問​​題はそれだけではありません。真剣に考え直すべきです。

于 2014-10-11T19:07:26.893 に答える