八皇后問題Java版

來源:互聯網
上載者:User

最近跳槽,新公司新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("----------------------------------------------");
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.