Leetcode 51 Solution

This article provides solution to leetcode question 51 (n-queens)

https://leetcode.com/problems/n-queens

Solution

class Solution { vector<vector<string>> m_res; public: void solveNQueens(vector<int>& board, int n, int layer) { if (board.size() == layer) { vector<string> res;
for (int i = 0; i < board.size(); i++) { string str = string(board[i], '.') + "Q" + string(n - board[i] - 1, '.'); res.push_back(str); }
m_res.push_back(res); return; }
for (int i = 0; i < n; i++) { board[layer] = i;
bool valid = true; for (int j = 0; j < layer; j++) { if (board[j] == i || abs(board[j] - i) == abs(j - layer)) { valid = false; break; } }
if (valid) solveNQueens(board, n, layer + 1); } }
vector<vector<string>> solveNQueens(int n) { vector<int> board(n, -1); solveNQueens(board, n, 0); return m_res; } };