首页 > 代码库 > [CC150] 八皇后问题

[CC150] 八皇后问题

Write an algorithm to print all ways of arranging eight queens on an 8*8 chess board so that none of them share the same row, column or diagonal.

思路:

本质上是DFS, 从第一行开始一行行地放棋子,每次放棋子之前根据当前的棋盘检查一下约束。

Code (from book):

    void placeQueen(int row, Integer[] columns, ArrayList<Integer[]> result){
        if(row == GRID_SIZE){
            result.add(columns.clone());
            return;
        }
        
        for(int col = 0; col < GRID_SIZE; ++col){
            if(checkValid(row, col, columns)){
                columns[row] = col;
                placeQueen(row + 1, columns, result);
            }
        }
    }
    
    // No need to check the same row because the program
    // proceeds one row at a time
    boolean checkValid(int row, int column, Integer[] columns){
        for(int i = 0; i < row; ++i){
            int j = columns[i];
            
            // check the same column
            if(column == j){
                return false;
            }
            
            // check same diagonal
            if(Math.abs(row - i) == Math.abs(column - j)){
                return false;
            }
        }
        return true;
    }