|
| 1 | + |
| 2 | +#include <iostream> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +char board[30][30]; |
| 6 | + |
| 7 | +void printBoard(char arr[][30], int n) { |
| 8 | + for (int r = 0; r < n; ++r) { |
| 9 | + for (int c = 0; c < n; ++c) { |
| 10 | + cout << arr[r][c] << " " ; |
| 11 | + } |
| 12 | + cout << endl; |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +void initialiseBoard(int n) { |
| 17 | + for (int r = 0; r < n; ++r) { |
| 18 | + for (int c = 0; c < n; ++c) { |
| 19 | + board[r][c] = 'X'; |
| 20 | + } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +bool canPlace(char board[][30], int N, int x, int y) |
| 25 | +{ |
| 26 | + //check the row if aqueen already exists |
| 27 | + for (int r = 0; r < N; ++r) |
| 28 | + { |
| 29 | + if (board[r][y] == 'Q') |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + int rInc[] = { -1, +1, +1, -1}; |
| 34 | + int cInc[] = { -1, +1, -1, +1}; |
| 35 | + //check diagonal if queen already exists |
| 36 | + for (int dir = 0; dir < 4; ++dir) |
| 37 | + { |
| 38 | + int rowAdd = rInc[dir]; |
| 39 | + int colAdd = cInc[dir]; |
| 40 | + int r = x + rowAdd; |
| 41 | + int c = y + colAdd; |
| 42 | + //check that r c is within the board |
| 43 | + while (r >= 0 && r < N && c >= 0 && c < N) |
| 44 | + { |
| 45 | + if (board[r][c] == 'Q') |
| 46 | + return false; |
| 47 | + r = r + rowAdd; |
| 48 | + c = c + colAdd; |
| 49 | + } |
| 50 | + } |
| 51 | + return true; |
| 52 | +} |
| 53 | + |
| 54 | +bool nqueen(int r, int n) |
| 55 | +{ |
| 56 | + if (r == n)//base case if all queens are placed |
| 57 | + { |
| 58 | + return true; |
| 59 | + } |
| 60 | + //for every column, use hit and trial by placing a queen in the each cell of curr Row |
| 61 | + for (int c = 0; c < n; ++c) |
| 62 | + { |
| 63 | + int x = r; |
| 64 | + int y = c; |
| 65 | + //check if queen can be placed on board[i][c] |
| 66 | + if (canPlace(board, n, x, y)==true) |
| 67 | + { |
| 68 | + board[x][y] = 'Q'; //place queen in each column |
| 69 | + bool isSuccessful = nqueen(r + 1, n); //recursion to place rest of queens |
| 70 | + if (isSuccessful == true) |
| 71 | + return true; |
| 72 | + board[x][y] = 'X'; //else unmark the cell or backtrack |
| 73 | + } |
| 74 | + } |
| 75 | + return false; //if queen cannot be placed in any row in this column then return false |
| 76 | +} |
| 77 | + |
| 78 | +int main() |
| 79 | +{ |
| 80 | + int n; |
| 81 | + cin >> n; |
| 82 | + |
| 83 | + initialiseBoard(n);//initialse all the board with X |
| 84 | + bool isSuccessful = nqueen(0, n); |
| 85 | + |
| 86 | + if (isSuccessful) printBoard(board, n); |
| 87 | + else cout << "Sorry man! You need to have a larger board!\n"; |
| 88 | + |
| 89 | + return 0; |
| 90 | +} |
0 commit comments