【问题标题】:Getting every combination of Queens?获得所有皇后组合?
【发布时间】: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


【解决方案1】:

这就是为什么你会立即得到零的原因:

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

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

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

【讨论】:

  • 我接受了你的批评并重写了它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
相关资源
最近更新 更多