N皇后的问题——算法的思想:回溯和剪枝
生活随笔
收集整理的這篇文章主要介紹了
N皇后的问题——算法的思想:回溯和剪枝
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.dym;public class Queens {public static void main(String[] args) {// TODO Auto-generated method stubnew Queens().placeQueens(4);}/*** 數組索引是行號,數組元素是列號*/int[] cols;/*** 一共有多少種擺法*/int ways;void placeQueens(int n) {if (n < 1) return;cols = new int[n];place(0);System.out.println(n + "皇后一共有" + ways + "種擺法");}/*** 從第row行開始擺放皇后* @param row*/void place(int row) {if (row == cols.length) {ways++;show();return;}for (int col = 0; col < cols.length; col++) {if (isValid(row, col)) {// 在第row行第col列擺放皇后cols[row] = col;place(row + 1);}}}/*** 判斷第row行第col列是否可以擺放皇后*/boolean isValid(int row, int col) {for (int i = 0; i < row; i++) {// 第col列已經有皇后if (cols[i] == col) {
// System.out.println("[" + row + "][" + col + "]=false");return false;}// 第i行的皇后跟第row行第col列格子處在同一斜線上if (row - i == Math.abs(col - cols[i])) {
// System.out.println("[" + row + "][" + col + "]=false");return false;}}
// System.out.println("[" + row + "][" + col + "]=true");return true;}void show() {for (int row = 0; row < cols.length; row++) {for (int col = 0; col < cols.length; col++) {if (cols[row] == col) {System.out.print("1 ");} else {System.out.print("0 ");}}System.out.println();}System.out.println("------------------------------");}
}
總結
以上是生活随笔為你收集整理的N皇后的问题——算法的思想:回溯和剪枝的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AOP原理-创建AOP代理--Annot
- 下一篇: 声明式事务--@EnableTransa