51. N-Queens

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 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.

Solutions:

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

    vector<string> generateSolution(vector<int>& path) {
        int n = path.size();
        string row = string(n, '.');
        vector<string> solution;
        for (int i = 0; i < n; ++i) {
            solution.push_back(row);
            solution.back()[path[i]] = 'Q';
        }
        return solution;
    }

    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, vector<vector<string>>& ret) {
        if (n == pos) {
            ret.push_back(generateSolution(path));
            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 ""