The n-queens Puzzle is the problem of placing N Queens on anxn chessboard such that n o The Queens attack each of the 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 Indic Ate a queen and an empty space respectively.
For example,
There exist-distinct solutions to the 4-queens puzzle:
[ [". Q.. ", //solution 1 " ... Q ", " Q ... ",". . Q. "], ["]. Q. ", //Solution 2 " Q ... ", " ... Q ", ". Q.. "]
#include <iostream> #include <vector> #include <string>using namespace std;vector<string> Queenslayout (vector< vector<int> >& chessboard) {vector<string> res; for (int i = 0; i < chessboard.size (); ++i) {String tmp = ""; for (int j = 0; J < chessboard[i].size (); ++j) {if (chessboard[i][j] = = 1) TMP = tmp + "Q"; else tmp + = "."; } res.push_back (TMP); } return res; BOOL Checkrows (vector< vector<int> >& chessboard, int i, int dep) {int tmp = 0; Just need to check until the dep-th column for (int k = 0; k < dep; ++k) {tmp + = Chessboard[i][k]; } return TMP = = 0;} BOOL Checkcols (vector< vector<int> >& chessboard, int i, int dep) {int tmp = 0; Just need to check until the i-th row for (int k = 0; k < i; ++k) {tmp + = CHESSBOARD[K][DEP]; } return TMP = = 0;} BOOL Checkdiag (vector< vector<int> >& chessboard, int i, int dep) { int tmp = 0;&NBSp int row = i, col = dep; //Check left-up diag. while (row >= 0 && col >= 0) { t MP + = chessboard[row][col]; row--; col--; } if (tmp > 1) return false; TMP = 0; row = i, col = dep; //Check Left-down diag. while (Row < Chessboard.size () && Col >= 0) { tmp + = chessboard[row][col]; row++; col--; } return TMP = = 1;} BOOL Noconflict (vector< vector<int> >& chessboard, int i, int dep) { return checkrows (chessboard, I, DEP) && Checkcols (chessboard, I, DEP) && Checkdiag (chessboard, I, DEP);} void Solvequeens (vector< vector<int> >& chessboard, vector< vector<string> >& res, int DEP) { if (dep = = Chessboard.size ()) { vector<string> tmp = queenslayout (chessboard); res.push_back (TMP); return; } for (int i = 0; i < chessboard.size (); ++i) { CHESSBOARD[I][DEP] = 1; if (noconflict (chessboard, I, DEP)) { Solvequeens (ChessBoard, Res, dep+1); } CHESSBOARD[I][DEP] = 0; }}vector< vector<string> > Solvequeens (int n) { vector< vector<int> > Chessboard (n, vector<int> (n, 0)); vector< vector<string> > res; solvequeens (Chessboard, res, 0); return res; int main (void) { vector< vector<string> > Res = solvequeens (4); for (int i = 0; i < res.size (); ++i) { for (int j = 0; J < res[i].size (); ++j) { cout << Res[i][j] << endl; } cout << endl; }}
Leetcode 51. N-queens