PROBLEM N - Queens problem is to place n - queens in such a manner on an n x n chessboard that no queens attack each other by being in the same row, column or diagonal.
Note: solution exist for all natural number n with
the exception of n=2 and n=3 Time Complexity: O(n!) bool solveNQUtil(int board[N][N], int col) bool isSafe(int board[N][N], int row, int col) { /* base case: If all queens are placed then return true */ { //if we are here that means we have solved the problem int i, j; if (col >= N) return true; /* Check this row on left side */ /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { for (i = 0; i < col; i++) if (board[row][i]==1) /* Check if the queen can be placed on board[i][col] */ return false; if (isSafe(board, i, col)) {
/* Check upper diagonal on left side */ /* Place this queen in board[i][col] */
board[i][col] = 1; for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]==1) /* recur to place rest of the queens */ return false; if (solveNQUtil(board, col + 1)) return true; /* Check lower diagonal on left side */ /* If placing queen in board[i][col] doesn't lead to a solution, then remove for (i = row, j = col; j >= 0 && i < N; i++, j--) queen from board[i][col] */ if (board[i][j]==1) board[i][col] = 0; return false; } } return true; /* If the queen cannot be placed in any row in this colum col then return false } */ return false;