BiruLyu
5/30/2017 - 5:29 PM

51. N-Queens.java

public class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>>res = new ArrayList<List<String>>();
        if(n <= 0) return res;
        List<Integer> positions = new ArrayList<Integer>();
        backtracking(res, positions, n);
        return res;
        
    }
    
    private void backtracking(List<List<String>> res, List<Integer> positions, int n) {
        if(positions.size() == n) {
            res.add(drawChessboard(positions));
        }
        for (int colIndex = 0; colIndex < n; colIndex++) {
            if(!isValid(positions, colIndex)) {
                continue;
            }
            positions.add(colIndex);
            backtracking(res, positions, n);
            positions.remove(positions.size() - 1);
        }
    }
    private boolean isValid(List<Integer> positions, int curCol) {
        int curRow = positions.size();
        int sum = curCol + curRow;
        int diff = curRow - curCol;
        for(int tempRow = 0; tempRow < curRow; tempRow++) {
            int tempCol = positions.get(tempRow);
            int tempSum = tempCol + tempRow;
            int tempDiff = tempRow - tempCol;
            if (curCol == tempCol || sum == tempSum || diff == tempDiff) {
                return false;
            }
        }
        return true;
    }
    private List<String> drawChessboard(List<Integer> positions) {
        List<String> res = new ArrayList<String>();
        int len = positions.size();
        for(int i = 0; i < len; i++) {
            StringBuilder temp = new StringBuilder();
            for (int j = 0; j < len; j++) {
                temp.append(j == positions.get(i) ? 'Q' : '.');
            }
            res.add(temp.toString());
        }
        return res;
    }
}