遞歸求N皇后

遞歸求N皇后(java)

 

package dane.queen.com;

/*

 * @author dane-zhu

 * 遞歸求N皇后,2011.2.22

 */

public class Queen {

    private final  static  int N = 8;

    private static char[][] matrix = new char[N][N];

    private static int x;

    private static int sum;

 

    public Queen() {

        for(int i = 0 ;i < N;i++){

            for(int j = 0; j < N;j++){

                matrix[i][j] = '*';

            }

        }

        x = 0;

        sum = 0;

    }

 

    private Boolean check(char[][] m,int x,int y){

        for(int i = 0 ;i < N;i++){

            for(int j = 0; j < N;j++){

                //判斷上下左右有沒有'Q'

                if(m[i][y] == 'Q' || m[x][j] == 'Q')

                    return false;

                //判斷上斜線上有沒有'Q'

                if((i != x && j != y) && ((i - x)/(j - y * 1.0)  == 1.0 ||(i - x)/(j - y * 1.0)  == -1.0)){

                    if(m[i][j] == 'Q')

                        return false;

                }

            }

        }

        return true;

    }

 

    private void find(char[][] m,int x){

        if(x == N){

            sum++;

            print(m);

            return;

        }

        for(int i = 0;i < N;i++){

            if(check(m, x, i) == true){               

                m[x++][i] = 'Q';

                //遞歸查找

                find(m, x);

                m[--x][i] = '*';

            }

        }

        return;

    }

 

    private void print(char[][] m){

        System.out.println("Solve of " + sum);

        for(int i = 0 ;i < N;i++){

            for(int j = 0; j < N;j++){

                System.out.print(m[i][j] + " ");

            }

             System.out.println();

        }

    }

 

    public static void main(String[] args){

        Queen queen = new Queen();

        queen.find(matrix, x);

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章