八皇后问题 --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);
    }
}


 

你可能感兴趣的:(八皇后问题 --java)