Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1443125
  • 博文数量: 3500
  • 博客积分: 6000
  • 博客等级: 准将
  • 技术积分: 43870
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-03 20:31
文章分类

全部博文(3500)

文章存档

2008年(3500)

我的朋友

分类:

2008-05-04 23:43:22

一起学习
自己写的MN皇后程序,希望对大家有用。
size是棋盘大小,numberOfQueens是皇后个数,约束是每个皇后的每行每列以及对角线上不允许出现皇后。
public class QueensMN{
public static void main(String[] argu){
int size = 8;
int numberOfQueens = 8;
int count = 0;
int[] a = new int[size];
for(int i = 0 ; i< size ; i ){a
= -1;}
a[0] = 0;
int length = 0;
String output = "";
while(true){
if (length < 0) {System.out.println("Game Over ");break;}
if ( count == numberOfQueens && isValid(a,length) ) {output = "";//for (int i = 0 ; i < size ; i ) output = a
;System.out.println(output);
p(a);System.out.println();a[length] ;count--;continue;}
else if(a[length] > size - 1){
if(length == size - 1){
a[length] = -1;
length --;
while(length >= 0 && a[length] == -1)
{
length --;
}
if(length < 0) continue;
else {a[length] ;count--;continue;}
}
else{
if(numberOfQueens - count > size - 1 - length ){
a[length] = -1;
length --;
while(length >= 0 && a[length] == -1)
{
length --;
}
if(length < 0) continue;
else {a[length] ;count--;continue;}

}
else{
a[length] = -1;
length ;
a[length] = 0;
continue;

}
}
}
else if (!isValid(a,length)){
a[length] ;
}
else {
count ;
if(count == numberOfQueens) continue;
else {length ;a[length] = 0;}
}
}
}
public static boolean isValid(int[] a,int m) {
for(int i = 0; i < m; i ){
if(a[m] == -1) return true;
if(a
== -1) continue;
if (a
== a[m]) return false;
if (java.lang.Math.abs(m - i ) == java.lang.Math.abs(a
- a[m])) return false;
}
return true;
}
public static void p(int[] a ){
String s ="";
for(int i = 0;i < a.length;i ){
for (int j = 0; j < a.length;j ){
if (a.length - 1 - i == a[j]) s = "Q";
else s = "*";
}
s ="\n";
}
System.out.print(s);

}
}

QueensMN.rar
(2008-03-13 09:58:16, Size: 750 B , Downloads: 6)

TAG: MN皇后

下载本文示例代码


MN皇后MN皇后MN皇后MN皇后MN皇后MN皇后MN皇后MN皇后MN皇后MN皇后MN皇后MN皇后
阅读(655) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~