@@ -139,4 +139,73 @@ function printBoard (chessBoard) {
139139}
140140
141141nqueens (8 );
142- ```
142+ ```
143+
144+ ## C++ Implementation
145+
146+ ### [ Solution 1] ( ./C++/Day17.cpp )
147+
148+ ``` cpp
149+ /*
150+ * @author : dhruv-gupta14
151+ * @date : 12/01/2019
152+ */
153+
154+ #include < iostream>
155+ using namespace std ;
156+ #define N 8
157+
158+ void printBoard (int board[ N] [ N ] ) {
159+ for (int i = 0; i < N; i++) {
160+ for (int j = 0; j < N; j++)
161+ cout << board[ i] [ j ] << " ";
162+ cout << endl;
163+ }
164+ }
165+
166+ bool isValid(int board[ N] [ N ] , int row, int col) {
167+ for (int i = 0; i < col; i++) //check whether there is queen in the left or not
168+ if (board[ row] [ i ] )
169+ return false;
170+ for (int i=row, j=col; i>=0 && j>=0; i--, j--)
171+ if (board[ i] [ j ] ) //check whether there is queen in the left upper diagonal or not
172+ return false;
173+ for (int i=row, j=col; j>=0 && i<N; i++, j--)
174+ if (board[ i] [ j ] ) //check whether there is queen in the left lower diagonal or not
175+ return false;
176+ return true;
177+ }
178+
179+ bool solveNQueen(int board[ N] [ N ] , int col) {
180+ if (col >= N) //when N queens are placed successfully
181+ return true;
182+ for (int i = 0; i < N; i++) { //for each row,check placing of queen is possible or not
183+ if (isValid(board, i, col) ) {
184+ board[ i] [ col ] = 1; //if validate, place the queen at place (i, col)
185+ if ( solveNQueen(board, col + 1)) //Go for the other columns recursively
186+ return true;
187+
188+ board[ i] [ col ] = 0; //When no place is vacant remove that queen
189+ }
190+ }
191+ return false;
192+ }
193+
194+ bool checkSolution() {
195+ int board[ N] [ N ] ;
196+ for(int i = 0; i<N; i++)
197+ for(int j = 0; j<N; j++)
198+ board[ i] [ j ] = 0;
199+
200+ if ( solveNQueen(board, 0) == false ) {
201+ cout << "Solution does not exist";
202+ return false;
203+ }
204+ printBoard(board);
205+ return true;
206+ }
207+
208+ int main() {
209+ checkSolution();
210+ }
211+ ```
0 commit comments