编程基础--八皇后问题

来源:互联网 发布:上瘾2网络剧台湾版网盘 编辑:程序博客网 时间:2024/05/12 09:10

八皇后问题是一个以国际象棋为背景的问题:如何能够在 8×8的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一条横行、纵行或斜线上。八皇后问题可以推广为更一般的n皇后摆放问题:这时棋盘的大小变为n1×n1,而皇后个数也变成n2。而且仅当n2 = 1 或 n1 ≥ 3 时问题有解。

这里写图片描述

/** * Created by hasee on 2017/8/21. */public class Demo1 {    static int TURE =1,FALSE =0,EIGHT =8;    static int[] queen =new int[EIGHT];  //存放八个皇后的位置    static int number =0;  //计算共有几组解    /**     * 放置是否正确(不跟其他皇后在相同对角线或者直线上)     * @param row     * @param col     * @return     */    public static int isRight(int row ,int col){        int i = 0, right =FALSE;        int offset_col = 0,offset_row =0;        while(right != 1 && i < col){            offset_col = Math.abs(i - col);            offset_row = Math.abs(queen[i] -row);            //判断两皇后是否在同一列或者在同一对角线上            if(queen[i] == row  || offset_col ==offset_row)                right =TURE;            i++;        }        return  right;    }    /**     * 对八个皇后进行排放     * @param value     */    public static void  put(int value){        int i=0;        while(i < EIGHT){            if(isRight(i,value) != 1){                queen[value] = i;                if(i == 7){                    print_table();                }else {                    put(value+1);   //针对每一col进行一个测试                }            }            i++;        }    }    public static void print_table(){       number++;        System.out.println("第"+number+"组解为:");        for(int i = 0 ; i < EIGHT ; i++){            for(int j = 0; j < EIGHT ; j++){                if(queen[i] == j){                    System.out.print("<*>");                }else{                    System.out.print("<->");                }            }            System.out.println();        }    }    public static void main(String[] args) {        Demo1.put(0);    }}
原创粉丝点击