N-Queens Solutions in C++
Number 51
Difficulty Hard
Acceptance 46.8%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/n-queens/// Author : Hao Chen// Date : 2014-08-22#include <stdlib.h>#include <iostream>#include <vector>#include <string>using namespace std;vector< vector<string> > solveNQueens(int n);void solveNQueensRecursive(int n, int currentRow, vector<int>& solution, vector< vector<string> >& result);bool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn);vector< vector<string> > solveNQueens(int n) {vector< vector<string> > result;vector<int> solution(n);solveNQueensRecursive(n, 0, solution, result);return result;}//The following recursion is easy to understand. Nothing's tricky.// 1) recursively find all of possible columns row by row.// 2) solution[] array only stores the columns index. `solution[row] = col;`void solveNQueensRecursive(int n, int currentRow, vector<int>& solution, vector< vector<string> >& result) {//if no more row need to do, shape the resultif (currentRow == n){vector<string> s;vector<string> s(n, string(n, '.'));for (int row = 0; row < n; row++) {s[row][solution[row]] = 'Q';}result.push_back(s);return;}//for each columnfor (int col = 0; col < n; col++) {//if the current column is validif (isValid(col, currentRow, solution) ) {//place the Queuesolution[currentRow] = col;//recursively put the Queen in next rowsolveNQueensRecursive(n, currentRow+1, solution, result);}}}//Attempting to put the Queen into [row, col], check it is valid or not//Notes:// 1) we just checking the Column not Row, because the row cannot be conflicted// 2) to check the diagonal, we just check |x'-x| == |y'-y|, (x',y') is a Queen will be placedbool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn) {for(int i=0; i<attemptedRow; i++) {if (attemptedColumn == queenInColumn[i] ||abs(attemptedColumn - queenInColumn[i]) == abs(attemptedRow - i)) {return false;}}return true;}void printMatrix(vector< vector<string> >& matrix ){for (int i = 0; i < matrix.size(); i++) {cout << "-----------" << endl;for (int j = 0; j < matrix[i].size(); j++) {cout << matrix[i][j] << endl;}}}int main(int argc, char** argv){int n = 8;if (argc>1){n = atoi(argv[1]);}vector< vector<string> > result = solveNQueens(n);printMatrix(result);return 0;}
C++ solution by pezy/LeetCode
#include <vector>#include <string>using std::vector; using std::string;class Solution {vector<vector<string>> ret;public:vector<vector<string> > solveNQueens(int n) {vector<int> queens(n, 0);solveNQueens(0, queens);return ret;}void solveNQueens(int row, vector<int> queens) {int size = queens.size();if (row == size) {vector<string> solution(size, string(size, '.'));for (int r=0; r<size; ++r)solution[r][queens[r]] = 'Q';ret.push_back(solution);} else for (int col=0; col<size; ++col) {queens[row] = col;if (isValid(row, col, queens)) solveNQueens(row+1, queens);}}bool isValid(int row, int col, const vector<int> &queens) {for (int queen_col=0, r=row-1, lc=col-1, rc=col+1; r>=0; --r, --lc, ++rc) {queen_col = queens[r];if (queen_col == col || queen_col == lc || queen_col == rc) return false;}return true;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/n-queens/description//// Author : liuyubobobo/// Time : 2017-11-18#include <iostream>#include <vector>#include <cassert>using namespace std;/// Basic Recursive/// Time Complexity: O(n^n)/// Space Complexity: O(n)class Solution {private:vector<bool> col, dia1, dia2;vector<vector<string>> res;// 尝试在一个n皇后问题中, 摆放第index行的皇后位置void putQueen(int n, int index, vector<int> &row){if(index == n){res.push_back(generateBoard(n, row));return;}for(int i = 0 ; i < n ; i ++)// 尝试将第index行的皇后摆放在第i列if(!col[i] && !dia1[index + i] && !dia2[index - i + n - 1]){row.push_back(i);col[i] = true;dia1[index + i] = true;dia2[index - i + n - 1] = true;putQueen(n, index + 1, row);col[i] = false;dia1[index + i] = false;dia2[index - i + n - 1] = false;row.pop_back();}return;}vector<string> generateBoard(int n, vector<int> &row){assert(row.size() == n);vector<string> board(n, string(n, '.'));for(int i = 0 ; i < n ; i ++)board[i][row[i]] = 'Q';return board;}public:vector<vector<string>> solveNQueens(int n) {res.clear();col.clear();for(int i = 0 ; i < n ; i ++)col.push_back(false);dia1.clear();dia2.clear();for(int i = 0 ; i < 2 * n - 1 ; i ++){dia1.push_back(false);dia2.push_back(false);}vector<int> row;putQueen(n, 0, row);return res;}};void printBoard(const vector<string>& board){for(string row: board)cout << row << endl;cout << endl;}int main() {int n = 4;vector<vector<string>> res = Solution().solveNQueens(n);for(vector<string> board: res)printBoard(board);return 0;}