Java解8皇后问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package algs; /** * Author: areful * Date: 2018/8/9 */ public class Queen8 { private static final int MAX_QUEEN = 8 ; private int [] cols = new int [MAX_QUEEN]; private int num = 0 ; private void calc() { getArrangement( 0 ); System.out.println(MAX_QUEEN + "皇后问题有" + num + "种摆放方法。" ); } private void getArrangement( int n) { boolean [] rows = new boolean [MAX_QUEEN]; 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 <= MAX_QUEEN - 1 ) rows[cols[i] + d] = true ; } for ( int i = 0 ; i < MAX_QUEEN; i++) { if (rows[i]) continue ; cols[n] = i; if (n < MAX_QUEEN - 1 ) { getArrangement(n + 1 ); } else { num++; printChessBoard(); } } } private void printChessBoard() { System.out.println( "第" + num + "种走法" ); for ( int i = 0 ; i < MAX_QUEEN; i++) { for ( int j = 0 ; j < MAX_QUEEN; j++) { if (i == cols[j]) { System.out.print( "0 " ); } else System.out.print( ". " ); } System.out.println(); } } public static void main(String[] args) { new Queen8().calc(); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步