52. N-Queens II

  • Difficulty: Hard

  • Topics: Backtracking

  • Similar Questions:

Problem:

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 the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

Solutions:

class Solution {
public:
    int totalNQueens(int n) {
        int ret = 0;
        vector<int> path;
        vector<bool> colVisited (n, false);
        helper(n, 0, path, colVisited, ret);
        return ret;
    }

    bool diagonal(int row, int col, vector<int>& path) {
        int n = path.size();
        for (int i = 0; i < n; ++i) {
            if (abs(row - i) == abs(col - path[i])) return true;
        }
        return false;
    }

    void helper(int n, int pos, vector<int>& path, vector<bool>& colVisited, int& ret) {
        if (n == pos) {
            ++ret;
            return;
        }

        for (int i = 0; i < n; ++i) {
            if (colVisited[i] || diagonal(pos, i, path)) continue;
            path.push_back(i);
            colVisited[i] = true;
            helper(n, pos + 1, path, colVisited, ret);
            colVisited[i] = false;
            path.pop_back();
        }
    }
};

results matching ""

    No results matching ""