八皇后问题Java版

来源:互联网 发布:磊科 网络尖兵配置 编辑:程序博客网 时间:2024/05/18 01:58

最近跳槽,新公司新team,本来打算做一个超级大的平台转移项目,但是调研的人去西藏玩了,整个项目只能延迟到11月份才开始。

于是做一些无聊的事情,优化自动化测试,减少测试执行时间,测试环境还不稳定......

N天之后终于搞定了,调研的人回去休国庆假期,今天实在无聊,想想大学时候经典的汉诺塔,走台阶我都写过了,八皇后一直没写过。

用啥语言写呢,是个问题,我上个东家是做嵌入式的,所以c最顺手了,可是新东家没有比较好的IDE,编译也需要传到服务器上才可以,

果断放弃。erlang倒是适合递归,不过没数组类型,用list去检测也不方便,只能java了,打开eclipse,懒得新建工程,直接在以前练习

设计模式里的一个类里直接加main,经过一个半小时的coding,终于成型了



package com.df.design.brige;


public class BrigeMain {


/**
* @param args
*/


public static int fb = 8;
   
public static int count =0;

public static void main(String[] args) {


int tposition[][] = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
process(tposition, 0); 
System.out.println(count);
}


public static void process(int mr[][], int curstep) {
if (curstep == fb) {
printResult(mr);
count++;
return;
}
int step = 0;
for (; step < fb; step++) {
if (lineuUnique(mr, curstep, step)
&& diagonalUniqueDown(mr, curstep, step)
&& diagonalUniqueUp(mr, curstep, step)) {
mr[curstep][step] = 1;
process(mr, curstep + 1);
mr[curstep][step] = 0;


}
}

}


public static boolean lineuUnique(int mr[][], int curstep, int tryline) {
if (curstep == 0)
return true;
int i = 0;
for (; i < curstep; i++) {
if (mr[i][tryline] == 1) {
return false;
}
}
return true;
}


public static boolean diagonalUniqueDown(int mr[][], int curstep, int trylin) {
if (curstep == 0)
return true;
int i = trylin - 1;
int j = curstep - 1;
while (i >= 0 && j >= 0) {
if (mr[j][i] == 1)
return false;
j--;
i--;
}
return true;
}


public static boolean diagonalUniqueUp(int mr[][], int curstep, int trylin) {
if (curstep == 0)
return true;
int i = trylin + 1;
int j = curstep - 1;
while (i < fb && j >= 0) {
if (mr[j][i] == 1)
return false;
j--;
i++;
}
return true;
}


public static void printResult(int result[][]) {


int i = 0;
for (; i < fb; i++) {
int j = 0;
for (; j < fb; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println("");


}
System.out.println("----------------------------------------------");
}
}

原创粉丝点击