N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> ans = new ArrayList<>();
        backTrack(n, ans, new ArrayList<String>(), 0);
        return ans;
    }

    public void backTrack(int n, List<List<String>> ans, ArrayList<String> temp, int row) {
        if (row == n) {
            ans.add(new ArrayList<>(temp));
            return;
        }
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < n; i++)
            str.append(".");
        for (int i = 0; i < n; i++) {
            if (isPossible(temp, row, i, n)) {
                str.setCharAt(i, 'Q');
                temp.add(str.toString());
                backTrack(n, ans, temp, row + 1);
                str.setCharAt(i, '.');
                temp.remove(temp.size() - 1);
            }
        }
    }

    public boolean isPossible(ArrayList<String> temp, int row, int col, int n) {
        for (int i = 0; i < row; i++) {
            if (temp.get(i).charAt(col) == 'Q')
                return false;
            int colValue1 = col - (row - i), colValue2 = col + (row - i);
            //checking diagonals
            if (colValue1 >= 0 && colValue1 < n && temp.get(i).charAt(colValue1) == 'Q')
                return false;
            if (colValue2 >= 0 && colValue2 < n && temp.get(i).charAt(colValue2) == 'Q')
                return false;
        }
        return true;
    }
}

Last updated