13. N-Queens II

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

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

Example 1:

Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.

Example 2:

Input: n = 1
Output: 1

Solution: (Backtracking)

class Solution
{
public:
    bool isSafe(int row, int col, int n, vector<vector<int>> &v)
    {

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (v[i][j] == 1)
                {
                    if (i == row || j == col || i + j == row + col || i - j == row - col)
                    {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    void findPos(int row, int n, vector<vector<int>> &v, int &count)
    {

        if (row == n)
        {
            count++;
            return;
        }

        for (int i = 0; i < n; i++)
        {
            if (isSafe(row, i, n, v))
            {
                v[row][i] = 1;
                findPos(row + 1, n, v, count);
                v[row][i] = 0;
            }
        }

        return;
    }

    int totalNQueens(int n)
    {

        vector<vector<int>> v(n, vector<int>(n, 0));
        int count = 0;
        findPos(0, n, v, count);

        return count;
    }
};

Time Complexity: O(n!)

Last updated