N-Queen Problem in C++ - GeeksforGeeks (2024)

Last Updated : 05 Aug, 2024

Summarize

Comments

Improve

The N-Queen problem is a classic puzzle where the goal is to place N queens on an N×N chessboard such that no two queens threaten each other. This means that no two queens can share the same row, column, or diagonal.

In this article, we will learn how to solve this problem using the C++ programming language.

Example:

Consider a 4×4 chessboard. The goal is to place 4 queens on the board such that no two queens can attack each other.

Input:

N-Queen Problem in C++ - GeeksforGeeks (1)

Solution:

N-Queen Problem in C++ - GeeksforGeeks (2)

To solve the N-Queen problem, we primarily use the Backtracking technique. Let’s discuss the approach and provide a C++ solution.

N Queen Problem usingBacktracking in C++

To solve N-Queen Problem we first place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes, then we backtrack and returnfalse.

Approach

  • Start with an N x N board initialized to all zeros, where N is the number of queens and the size of the board.
  • Define a function isSafe(board, row, col) to check if a queen can be placed at board[row][col] to ensure no other queens are in the same column, upper left diagonal, or upper right diagonal.
  • Define a function solveNQueens(board, row) to attempt placing queens on the board row by row.
  • If all queens are placed successfully (base case: row == N), return true.
  • For each column in the current row:
    • Check if placing a queen at board[row][col] is safe using isSafe().
    • If safe, place the queen (board[row][col] = 1).
    • Recur to place the next queen (solveNQueens(board, row + 1)).
    • If placing the queen leads to a solution, return true.
    • If not, remove the queen (board[row][col] = 0) and try the next column.
    • If the queen cannot be placed in any column in the current row, return false.
  • Print the solution if found, otherwise indicate no solution exists.

Below is the recursive tree of the above approach:

N-Queen Problem in C++ - GeeksforGeeks (3)

C++ Program to Solve N-Queen Problem using Backtracking

The following C++ program demonstrates how to solve the N-Queen problem using backtracking.

C++
// C++ program to solve N Queen Problem using backtracking#include <iostream>#define N 4using namespace std;// A utility function to print solutionvoid printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) if (board[i][j]) cout << "Q "; else cout << ". "; cout << "\n"; }}// A utility function to check if a queen can// be placed on board[row][col]. Note that this// function is called when "col" queens are// already placed in columns from 0 to col -1.// So we need to check only left side for// attacking queensbool isSafe(int board[N][N], int row, int col){ int i, j; // Check this row on left side for (i = 0; i < col; i++) if (board[row][i]) return false; // Check upper diagonal on left side for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; // Check lower diagonal on left side for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true;}// A recursive utility function to solve N// Queen problembool solveNQUtil(int board[N][N], int col){ // base case: If all queens are placed // then return true if (col >= N) return true; // Consider this column and try placing // this queen in all rows one by one for (int i = 0; i < N; i++) { // Check if the queen can be placed on // board[i][col] if (isSafe(board, i, col)) { // Place this queen in board[i][col] board[i][col] = 1; // recur to place rest of the queens if (solveNQUtil(board, col + 1)) return true; // If placing queen in board[i][col] // doesn't lead to a solution, then // remove queen from board[i][col] board[i][col] = 0; // BACKTRACK } } // If the queen cannot be placed in any row in // this column col then return false return false;}// This function solves the N Queen problem using// Backtracking. It mainly uses solveNQUtil() to// solve the problem. It returns false if queens// cannot be placed, otherwise, return true and// prints placement of queens in the form of 1s.// Please note that there may be more than one// solutions, this function prints one of the// feasible solutions.bool solveNQ(){ int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; if (solveNQUtil(board, 0) == false) { cout << "Solution does not exist"; return false; } printSolution(board); return true;}// Driver program to test above functionint main(){ solveNQ(); return 0;}

Output

. . Q . Q . . . . . . Q . Q . . 

Time Complexity:O(N!), where N is the number of queens. This is because in the worst case, the algorithm tries all possible placements.
Auxiliary Space:O(N2) for the board.

Further Optimization in isSafe() Function

The isSafe() function can be optimized by using additional arrays to keep track of the columns and diagonals under attack by any queen. This reduces the number of checks needed for each placement.

Optimized Approach:

  • Use three additional arrays: col[], diag1[], and diag2[] to keep track of the columns and diagonals.
  • Update these arrays when placing or removing a queen.

Below is the implementation of above optimized approach.

C++
// C++ program to solve N Queen Problem using backtracking#include <iostream>using namespace std;#define N 4// ld is an array where its indices indicate row-col+N-1// (N-1) is for shifting the difference to store negative// indicesint ld[30] = {0};// rd is an array where its indices indicate row+col// and used to check whether a queen can be placed on// right diagonal or notint rd[30] = {0};// Column array where its indices indicates column and// used to check whether a queen can be placed in that// row or not*/int cl[30] = {0};// A utility function to print solutionvoid printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << " " << (board[i][j] == 1 ? "Q" : ".") << " "; cout << endl; }}// A recursive utility function to solve N// Queen problembool solveNQUtil(int board[N][N], int col){ // Base case: If all queens are placed // then return true if (col >= N) return true; // Consider this column and try placing // this queen in all rows one by one for (int i = 0; i < N; i++) { // Check if the queen can be placed on // board[i][col] // To check if a queen can be placed on // board[row][col].We just need to check // ld[row-col+n-1] and rd[row+coln] where // ld and rd are for left and right // diagonal respectively if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { // Place this queen in board[i][col] board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; // Recur to place rest of the queens if (solveNQUtil(board, col + 1)) return true; // If placing queen in board[i][col] // doesn't lead to a solution, then // remove queen from board[i][col] board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } // If the queen cannot be placed in any row in // this column col then return false return false;}// This function solves the N Queen problem using// Backtracking. It mainly uses solveNQUtil() to// solve the problem. It returns false if queens// cannot be placed, otherwise, return true and// prints placement of queens in the form of 1s.// Please note that there may be more than one// solutions, this function prints one of the// feasible solutions.bool solveNQ(){ int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; if (solveNQUtil(board, 0) == false) { cout << "Solution does not exist"; return false; } printSolution(board); return true;}// Driver program to test above functionint main(){ solveNQ(); return 0;}

Output

 . . Q . Q . . . . . . Q . Q . . 

Time Complexity:O(N!)
Auxiliary Space:O(N)



M

mishraaabcf9

N-Queen Problem in C++ - GeeksforGeeks (4)

Improve

Previous Article

Sum of array using pointer arithmetic

Next Article

Knight’s Tour Problem in C++

Please Login to comment...

N-Queen Problem in C++ - GeeksforGeeks (2024)

FAQs

What is the solution to the n-queen problem? ›

Solution to the N-Queens Problem

We place one queen in each row/column. If we see that the queen is under attack at its chosen position, we try the next position. If a queen is under attack at all the positions in a row, we backtrack and change the position of the queen placed prior to the current position.

What is the n-queens problem in GFG? ›

We have discussed Knight's tour and Rat in a Maze problems in Set 1 and Set 2 respectively. Let us discuss N Queen as another example problem that can be solved using backtracking. The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.

What is the complexity of the n-queen problem? ›

For the first row, we check 'N' columns, for the second row, we check the N - 1 column and so on. Hence time complexity will be N * (N-1) * (N-2) …. i.e. N! O(N^2), where 'N' is the number of queens as we are using a 2-D array having N rows and N columns.

What is the 8 queen problem in C++? ›

8 Queens brute force problem is not printing out the results, C++ The 8 queens puzzle is a problem of placing 8 chess queens in each column on a chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row or diagonals.

Which algorithm is used to solve N queens problem? ›

The backtracking algorithm is used to solve the N queen problem, in which the board is recursively filled with queens, one at a time, and backtracked if no valid solution is found.

What is the advantage we get if we solve n queens problem? ›

It is useful for constraint satisfaction problems and involves systematically trying choices until finding one that "works". The eight queens problem, which involves placing eight queens on a chessboard so that none attack each other, is a classic example solved using backtracking.

Is n queens a hard problem? ›

The N-Queens problem is challenging in algorithm design, and discrete mathematics proved NP-complete even in the case of the completion problem Gent et al. (2017). It entails placing n queens on an n-by-n chessboard such that no two queens are under attack along any row, column, or diagonal.

What is the rule for the N queens problem? ›

No two queens on the same diagonal
  • The row number plus the column number for each of the two queens are equal. In other words, queens(j) + j has the same value for two different indices j .
  • The row number minus the column number for each of the two queens are equal.

What are the applications of N Queen problem? ›

The n-queen problem is an interesting problem in computer science because of its exponential complexity and real world applications such as VLSI testing, traffic control, constraint satisfaction problem, load balancing in a multiprocessor computer, etc.

Is n queen problem NP-Complete? ›

We show that n-Queens Completion is both NP-Complete and #P-Complete. A corollary is that any non-attacking arrangement of queens can be included as a part of a solution to a larger n-Queens problem.

Is N queens a constraint satisfaction problem? ›

We can represent the N-queens as a constraint satisfaction problem.

What is the N Queens problem representation? ›

The N-Queens problem can be defined aa follows: Place N queens on a N by N chessboard, one queen on each square, so that no queen apturea any other, that ia, the board configuration in which there exists at most one queen on the same row, column and diagonala. Figure 1 illustrates a solution to the 8-Queens problem.

What is the backtracking strategy for the 8 queens problem? ›

Backtracking Approach

Start in the leftmost column. If all queens are placed, then return true. Try all rows in the current column. For each row, if the queen can be placed safely in this row, then mark this cell and try to solve the problem recursively for the rest of the columns.

What is max min problem in C++? ›

The min and max functions in C++ are utility functions used to determine the smallest and largest values, respectively, from a given set of elements. These functions are part of the C++ Standard Library and can be applied to various data types, including integers, floating-point numbers, and custom objects.

Which of the following methods can be used to solve n queen's problem? ›

Which of the following methods can be used to solve n-queen's problem? Explanation: Of the following given approaches, n-queens problem can be solved using backtracking. It can also be solved using branch and bound.

What are the possible solutions of 4 queens? ›

That is, we get the solution (2, 4, 1, 3). This is one possible solution for the 4-queens problem. For another possible solution, the whole method is repeated for all partial solutions. The other solutions for 4 - queens problems is (3, 1, 4, 2) i.e.

What is the N queens completion problem? ›

The n-Queens problem is to place n chess queens on an n by n chessboard so that no two queens are on the same row, column or diagonal. The n-Queens Completion problem is a variant, dating to 1850, in which some queens are already placed and the solver is asked to place the rest, if possible.

What is the N Queens problem theory? ›

The N-Queens problem can be defined aa follows: Place N queens on a N by N chessboard, one queen on each square, so that no queen apturea any other, that ia, the board configuration in which there exists at most one queen on the same row, column and diagonala. Figure 1 illustrates a solution to the 8-Queens problem.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 5951

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.