Main recursive function.
| 65 | |
| 66 | // Main recursive function. |
| 67 | bool N_Queens(std::vector<std::vector<int>> &board, int n, int row) |
| 68 | { |
| 69 | // --> base case |
| 70 | // When row becomes equal to n |
| 71 | // means all queens have been placed in the right manner. |
| 72 | if (row == n) |
| 73 | { |
| 74 | // Print the first possible way. |
| 75 | printBoard(board, n); |
| 76 | // Endl for printing the next possible board |
| 77 | // std::cout << std::endl; |
| 78 | // Return true for returning to main. |
| 79 | return true; |
| 80 | // Return false for printing all possibilities. |
| 81 | // return false; |
| 82 | } |
| 83 | |
| 84 | // --> recursive case |
| 85 | for (int column = 0; column < n; ++column) |
| 86 | { |
| 87 | // Check if the queen can be placed at the ith row and jth column. |
| 88 | if (canBePlaced(board, row, column, n)) |
| 89 | { |
| 90 | // Mark that place as 1. |
| 91 | board[row][column] = 1; |
| 92 | // Check for further positions. |
| 93 | bool remaining_positions = N_Queens(board, n, row + 1); |
| 94 | if (remaining_positions) |
| 95 | { |
| 96 | // If queens can be placed in the remaining positions |
| 97 | // it means the placing of queens can proceed further. |
| 98 | // return true |
| 99 | return true; |
| 100 | } |
| 101 | else |
| 102 | { |
| 103 | // If queens cannot be placed further in the right way |
| 104 | // backtrack to the previous position. |
| 105 | board[row][column] = 0; |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | return false; |
| 111 | } |
| 112 | |
| 113 | int main() |
| 114 | { |
no test coverage detected