您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何基于java語(yǔ)言實(shí)現(xiàn)八皇后問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
八皇后問(wèn)題,在一個(gè)8X8的棋盤(pán)中,放置八個(gè)棋子,每個(gè)棋子的上下左右,左上左下,右上右下方向上不得有其他棋子。正確答案為92中,接下來(lái)用java語(yǔ)言實(shí)現(xiàn)。
代碼如下
package eightQuen; /** * 八皇后問(wèn)題 * * @author 83771 * */ public class eight { // 定義一個(gè)數(shù)組 表示棋盤(pán) public static Integer[][] checkerBoard = new Integer[8][8]; // 棋盤(pán)副本 public static Integer[][] checkerBoardCopy = new Integer[8][8]; // 計(jì)數(shù)器 用于計(jì)數(shù)有多少種方法 public static Integer jishu = 1; // 定義橫豎斜方向上是否有棋子 public static boolean flag1 = true; public static boolean flag2 = true; public static boolean flag3 = true; public static boolean flag4 = true; // 初始化一個(gè)棋盤(pán) 8x8 public static void init() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { System.out.print(0 + " "); checkerBoard[i][j] = 0; } System.out.println(); } checkerBoardCopy = checkerBoard; } // 遞歸測(cè)試方法 public static void startTest(int row) { for (int col = 0; col < 8; col++) { if (checkCheet(row, col, checkerBoardCopy) == 1) { if (row < 7) { startTest(++row); --row; } } // 該行重新賦值為0 進(jìn)行下一次判斷 checkerBoardCopy[row][col] = 0; } } // 檢查是否危險(xiǎn) // row行 // col列 public static int checkCheet(int row, int col, Integer[][] checkerBoardCopy) { flag1 = true; flag2 = true; flag3 = true; flag4 = true; // 行方向上是否滿(mǎn)足條件 for (int i = 0; i < 8; i++) { if (checkerBoardCopy[row][i] == 1) { flag1 = false; break; } } // 列方向上是否滿(mǎn)足條件 for (int j = 0; j < 8; j++) { if (checkerBoardCopy[j][col] == 1) { flag2 = false; break; } } // 右下方向 for (int i = row, j = col; i < 8 & j < 8; i++, j++) { if (checkerBoardCopy[i][j] == 1) { flag3 = false; break; } } // 左上方向 for (int i = row, j = col; i >= 0 & j >= 0; i--, j--) { if (checkerBoardCopy[i][j] == 1) { flag3 = false; break; } } // 左下方向 for (int i = row, j = col; i < 8 & j >= 0; i++, j--) { if (checkerBoardCopy[i][j] == 1) { flag4 = false; break; } } // 右上方向 for (int i = row, j = col; i >= 0 & j < 8; i--, j++) { if (checkerBoardCopy[i][j] == 1) { flag4 = false; break; } } if (flag1 & flag2 & flag3 & flag4) { // 若為真 增此點(diǎn)的值賦為1 checkerBoardCopy[row][col] = 1; // 如果已經(jīng)判斷到最后一行 并且最后一行也符合情況 打印整個(gè)棋盤(pán) if (row == 7) { printCheets(checkerBoardCopy); } return 1; } return 0; } // 打印棋盤(pán)方法 public static void printCheets(Integer[][] checkerBoardCopy) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { System.out.print(checkerBoardCopy[i][j] + " "); } System.out.println(); } System.out.println("=================" + jishu++); } public static void main(String[] args) { init(); startTest(0); } }
copy后可直接運(yùn)行。 記一下這次的代碼。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。