八皇后問題java代碼

來源:互聯網
上載者:User

標籤:

public class NQueens {public static int num = 0; // 累計方案總數public static final int MAXQUEEN = 5;// 皇后個數,同時也是棋盤行列總數public static int[] cols = new int[MAXQUEEN]; // 定義cols數組,表示n列棋子擺放情況public NQueens() {// 核心函數,從第0列開始getArrangement(0);System.out.println(MAXQUEEN + "皇后問題有" + num + "種擺放方法。");}public void getArrangement(int n) {// 遍曆該列所有不合法的行,並用rows數組記錄,不合法即rows[i]=trueboolean[] rows = new boolean[MAXQUEEN];for (int i = 0; i < n; i++) {rows[cols[i]] = true;int d = n - i;if (cols[i] - d >= 0)rows[cols[i] - d] = true;if (cols[i] + d <= MAXQUEEN - 1)rows[cols[i] + d] = true;}for (int k = 0; k < MAXQUEEN; k++) {// 判斷該行是否合法if (rows[k])continue;// 設定當前列合法棋子所在行數cols[n] = k;// 當前列不為最後一列時if (n < MAXQUEEN - 1) {getArrangement(n + 1);} else {// 累計方案個數num++;// 列印棋盤資訊printChessBoard();}}}public void printChessBoard() {System.out.println("第" + num + "種走法");for (int i = 0; i < MAXQUEEN; i++) {for (int j = 0; j < MAXQUEEN; j++) {if (i == cols[j]) {System.out.print("0 ");} elseSystem.out.print("+ ");}System.out.println();}}public static void main(String args[]) {NQueens queen = new NQueens();}}

參考文獻

http://blog.csdn.net/zhong317/article/details/4586131

http://zh.wikipedia.org/wiki/%E5%85%AB%E7%9A%87%E5%90%8E%E9%97%AE%E9%A2%98

八皇后問題java代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.