拉斯维加斯和回溯法解N皇后问题

雪花神剑 2011-05-06 08:22:39
package artificial;

import java.util.Random;
import java.util.Scanner;

public class LVQueen {
int n;
int[] x;
int[] y;

boolean place(int k){
for(int j=1;j<k;j++){
if((Math.abs(k-j)==Math.abs(x[j]-x[k]))||(x[j]==x[k]))
return false;
}
return true;
}
boolean backtrack(int t){
if(t>n){
for(int i=1;i<=n;i++)y[i]=x[i];
return true;
}
else{
for(int i=1;i<=n;i++){
x[t]=i;
if(place(t)&&backtrack(t+1))
return true;
}
return false;
}
}
boolean queenLV(int stepVegas){
Random rand=new Random();
int k=1;
int count=1;
while((k<=stepVegas)&&(count>0)){
count=0;
for(int i=1;i<=n;i++){
x[k]=i;
if(place(k))y[count++]=i;
}
System.out.println("count="+count);
if(count>0)x[k++]=y[rand.nextInt(count)];
}
return (count>0);
}
boolean nQueen(int n){
System.out.println(n);
x=new int[n+1];
y=new int[n+1];
for(int i=0;i<=n;i++){
x[i]=0;
y[i]=0;
}
int stop=2;//允许随机放置的皇后数
boolean found=false;
while(!queenLV(stop));//反复调用拉斯维加斯算法,直到找到解
System.out.println("循环结束");
if(backtrack(stop+1)){
for(int i=1;i<=n;i++){
System.out.print("("+i+","+x[i]+")");
found=true;
}
}
return found;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
long startTime=System.currentTimeMillis();
LVQueen lq=new LVQueen();
lq.nQueen(n);
long endTime=System.currentTimeMillis();
System.out.println("用时:"+(endTime-startTime)+"毫秒");

}
}
请各位高手看看,程序运行时语句 while(!queenLV(stop));无法结束,一直打印count=0,进入死循环。
...全文
448 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧