Created
August 2, 2019 09:54
-
-
Save Gaurav-Singh-97/b386f7bdec8650bb5a1cfdeb76eaac6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void placeQueen(vector<int>& colNo, vector<bool>& usedCol, vector<bool>& rowPlusCol, vector<bool>& rowMinusCol, int row, vector<vector<string>>& result) | |
{ | |
int n = usedCol.size(); | |
if (row == n) | |
{ | |
//all queens have been placed | |
vector<string> board(n, string(n, '.')); | |
int i; | |
for (i = 0; i < n; ++i) | |
board[i][colNo[i]] = 'Q'; | |
result.push_back(board); | |
return; | |
} | |
int c; | |
for (c = 0; c < n; ++c) | |
{ | |
if (!usedCol[c] && !rowPlusCol[row+c] && !rowMinusCol[row-c + n-1]) | |
{ | |
usedCol[c] = true; | |
rowPlusCol[row+c] = true; | |
rowMinusCol[row-c + n-1] = true; | |
colNo[row] = c; | |
placeQueen(colNo, usedCol, rowPlusCol, rowMinusCol, row+1, result); | |
colNo[row] = -1; | |
rowMinusCol[row-c + n-1] = false; | |
rowPlusCol[row+c] = false; | |
usedCol[c] = false; | |
} | |
} | |
} | |
class Solution { | |
public: | |
vector<vector<string>> solveNQueens(int n) { | |
vector<int> colNo(n, -1); | |
vector<bool> usedCol(n, false); | |
vector<bool> rowPlusCol(2*n, false), rowMinusCol(2*n, false); | |
vector<vector<string>> result; | |
placeQueen(colNo, usedCol, rowPlusCol, rowMinusCol, 0, result); | |
return result; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment