Solving the N Queen Problem with C - GangForCode (2024)

Solving the N-Queen Problem with C. The N-Queen Problem is a classic algorithmic challenge that involves placing N queens on an N*N chessboard so that no two queens can threaten each other. This means two queens can be in the same row, column, or diagonal. This article provides a step-by-step guide to solving the n queen problem with C language, focusing on a backtracking approach, which is a form of recursive algorithm.

Table of Contents

Understanding the N Queen Problem

Before jumping into coding, it is crucial to thoroughly understand what the n queen problem is and what it entails. the goal is to find all the problem arrangments of n queen on an n*n chessboard where no two queens attack each other.

Solving N Queen Problem with C

Defining the Chessboard

The chessboard can be represented as a 2D array of integers, where 0 indicates a space and 1 represents a queen.

int board[n][n];

Initializing the Chessboard

Before starting ensure that the chessboard is empty. this can be done with the simple nested loop

void initalizeBoard(int board[n][n]){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i][j] = 0; } }}

Check if the Queen can be Placed

We need a function to check if a queen can be placed on the board at the [row][col] position without being attacked by another queen.

int isSafe(int board[n][n], int row, int column){ int i, j; // Check this row on left side for (i = 0; i < column; i++) { if (board[row][i]) { return 0; } } // Check upper diagonal on upper side for (i = row, j = column; i >= 0 && j >= 0; i--, j--) { if (board[i][j]) { return 0; } } // Check lower diagonal on left side for (i = row, j = column; j >= 0 && i < n; i++, j--) { if (board[i][j]) { return 0; } } return 1;}

Solve the N Queen Problem

Use backtracking to solve the problem recursively. the function tries to place a queen on every row. if placing a queen in a certain column leads to the solution, it proceeds to place another queen in the next row. If it does not lead to a solution, it backtracks and tries a different column.

 int solvenqueen(int board[n][n], int column){ // Base case: If all queens are placed if (column >= n) { return 1; } // Consider this column and try placing this queen in all rows one by one for (int i = 0; i < n; i++) { // Chcek if queen can be placed on board[i][column] if (isSafe(board, i, column)) { // Place this queen on board[i][column] board[i][column] = 1; // Recur to place rest of the queens if (solvenqueen(board, column + 1)) { return 1; } // If placing queens in board[i][column] does not need to a solution, board[i][column] = 0; } } // if the queen can't be placed in any row in this column then return false return 0;}

Implement the Main Function

This function initializes the board and calls the utility function to solve the problem.

void main(){ printf("Enter the value of n "); scanf("%d", &n); int board[n][n]; initalizeBoard(board); if (!solvenqueen(board, 0)) { printf("Solution does not exist"); } else { printSolution(board); }}

Print the Solution

Implement a function to print the chessboard with a Queen place.

void printSolution(int board[n][n]){ printf("\n\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf(" %d ", board[i][j]); } printf("\n"); } printf("\n\n");}

Compelet C Program for N Queen Problem

#include <stdio.h>#include <stdlib.h>int n;void printSolution(int board[n][n]){ printf("\n\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf(" %d ", board[i][j]); } printf("\n"); } printf("\n\n");}int isSafe(int board[n][n], int row, int column){ int i, j; // Check this row on left side for (i = 0; i < column; i++) { if (board[row][i]) { return 0; } } // Check upper diagonal on upper side for (i = row, j = column; i >= 0 && j >= 0; i--, j--) { if (board[i][j]) { return 0; } } // Check lower diagonal on left side for (i = row, j = column; j >= 0 && i < n; i++, j--) { if (board[i][j]) { return 0; } } return 1;}int solvenqueen(int board[n][n], int column){ // Base case: If all queens are placed if (column >= n) { return 1; } // Consider this column and try placing this queen in all rows one by one for (int i = 0; i < n; i++) { // Chcek if queen can be placed on board[i][column] if (isSafe(board, i, column)) { // Place this queen on board[i][column] board[i][column] = 1; // Recur to place rest of the queens if (solvenqueen(board, column + 1)) { return 1; } // If placing queens in board[i][column] does not need to a solution, board[i][column] = 0; } } // if the queen can't be placed in any row in this column then return false return 0;}void initalizeBoard(int board[n][n]){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i][j] = 0; } }}void main(){ printf("Enter the value of n "); scanf("%d", &n); int board[n][n]; initalizeBoard(board); if (!solvenqueen(board, 0)) { printf("Solution does not exist"); } else { printSolution(board); }}

Output of N Queen Solution

n = 8

Solving the N Queen Problem with C - GangForCode (1)

n=12

Solving the N Queen Problem with C - GangForCode (2)

N Queen Problem Time Complexity

The backtracking approach for solving the n queen problem, as demonstrated in this article by using C language, does not have a straightforward time complexity due to its recursive nature and the fact that it explores multiple branches of execution, backtracking when a potential solution does not lead to success. The worst-case time complexity for the n queen problem using backtracking can be roughly estimated as O(n!) where n is the number of queens(or the size of the chessboard). This factorail time complexity arises because, in the worst case, the algorithm might need to try all possible arrangements of n queens on the board.

Happy Coding & Learning

See Also

  • C Program for Structure of Students Details
  • Circular Queue Implementation in C

Related

Solving the N Queen Problem with C - GangForCode (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 best algorithm for the N queen 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. At each step, the algorithm checks to see if the newly placed queen conflicts with any previously placed queens, and if so, it backtracks.

What are the diagonal conditions for the N queen problem? ›

No two queens on the same diagonal

First, if two queens lie on the same diagonal, one of the following conditions must be true: 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 .

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 is the first step in solving the n queen problem? ›

The idea is to 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.

What is the 8 * 8 N queen problem? ›

The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal. There are 92 solutions.

Can we solve N queen problem using dynamic programming? ›

The n-queens problem is to determine in how many ways n queens may be placed on an n-by-n chessboard so that no two queens attack each other under the rules of chess. We describe a simple O(ƒ(n)8n) solution to this problem that is based on dynamic programming, where ƒ(n) is a low-order polynomial.

What is the rule for the N queens problem? ›

The n-queens problem is to place n queens (where n > 0) on an n -by-n chessboard so that no queen is threatened by another one. According to the rules of chess, this is equivalent to the requirement that no two queens be on the same row or the same column or on a common diagonal.

What is the 4 queen problem? ›

The 4-queens problem consists of a 4x4 chessboard with 4 queens. The goal is to place the 4 queens on the chessboard such that no two queens can attack each other. Each queen attacks anything in the same row, in the same column, or in the same diagonal. Formulate the state of the 4-queens problem below.

What is the complexity of the N queen problem? ›

Hence, the time complexity will be N * (N-1) * (N-2) …. i.e. O(N!) O(N^2), where 'N' is the number of queens. We are using a 2-D array of size N rows and N columns, and also, because of Recursion, the recursive stack will have a linear space here.

What are the constraints of the N Queens 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. It can be seen that for n =1, the problem has a trivial solution, and no solution exists for n =2 and n =3.

What are the applications of N queen problem? ›

Although the n-queens problem is often commonly used as a benchmark for algorithms that solve combinatorial optimization problems; it has found several real-world applications, including practical task scheduling and assignment, computer resource management, and VLSI testing (P, 2011).

What is the best way to solve N queens? ›

N Queen Problem using Backtracking:

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 return false. Try all rows in the current column.

How many solutions are possible for the n-queens problem? ›

Standard mathematical techniques usually render the number of combinations to check down to N! (40320 for N=8). The number of "correct" non-attacking solutions is much smaller (92 when N=8).

What is the n-queens problem in combinatorics? ›

The N queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The backtracking Algorithm for N-Queen is already discussed here.

What is the aim of the N queens problem? ›

The goal of N Queens Problem is to suitably place N number of Queens on an N x N chessboard in a way that there is no conflict between them due to the arrangement, that is, there is no intersection between them vertically or horizontally or diagonally.

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.

How many distinct solutions are there in the N queen? ›

There are 12 unique solutions to this problem. Two solutions are not unique if you can ”mirror” one solution to find the other, or if you can rotate the board to find the other solution, or a combination of the two moves.

References

Top Articles
Latest Posts
Article information

Author: Rueben Jacobs

Last Updated:

Views: 5917

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Rueben Jacobs

Birthday: 1999-03-14

Address: 951 Caterina Walk, Schambergerside, CA 67667-0896

Phone: +6881806848632

Job: Internal Education Planner

Hobby: Candle making, Cabaret, Poi, Gambling, Rock climbing, Wood carving, Computer programming

Introduction: My name is Rueben Jacobs, I am a cooperative, beautiful, kind, comfortable, glamorous, open, magnificent person who loves writing and wants to share my knowledge and understanding with you.