八皇后问题 --java

 

package test;
public class EightQueen {
    String[][] rec = new String[8][8];

    int[] a = new int[8];

    int[] b = new int[15];

    int[] c = new int[15];

    int sum;

    public EightQueen() {
        super();
        for (int i = 0; i < this.rec.length; i++) {
            for (int j = 0; j < this.rec[i].length; j++) {
                this.rec[i][j] = “○”;
            }
        }

    }

    public void prt() {
        System.out.println(“”);
        for (int i = 0; i < this.rec.length; i++) {
            for (int j = 0; j < this.rec[i].length; j++) {
                System.out.print(this.rec[i][j] + ” “);
            }
            System.out.println(“”);
        }

        System.out.println(“”);
    }

    /**
     * set the queen of line i
     *
     * @param i
     */
    void qu(int i) {
        for (int iColumn = 0; iColumn < 8; iColumn++) {
            if (a[iColumn] == 0 && b[i – iColumn + 7] == 0
                    && c[i + iColumn] == 0) {
                // do not conflict
                rec[i][iColumn] = “●”;
                a[iColumn] = 1;
                b[i – iColumn + 7] = 1;
                c[i + iColumn] = 1;
//                prt();
                if (i < 7)
                    qu(i + 1);
                else {
                    // sysout
                    prt();
                    sum++;
                }
                // whatever how to put the queen, mission is impossible. rollback
                rec[i][iColumn] = “○”;
                a[iColumn] = 0;
                b[i – iColumn + 7] = 0;
                c[i + iColumn] = 0;
                prt();
               
            }
        }
    }

    /**
     * 8 queen
     * @param args
     */
    public static void main(String[] args) {
        EightQueen eq = new EightQueen();
        eq.qu(0);
        System.out.println(eq.sum);
    }
}

 

    原文作者:八皇后问题
    原文地址: https://blog.csdn.net/d_x_program/article/details/7349820
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞