N Queen Problem Using Branch and Bound in C
Last Updated :
14 Jul, 2024
N Queen Problem is a classic combinatorial problem. The objective is to place N queens on an N×N chessboard such that no two queens threaten each other according to the rules of the chess game. No two queens can share the same row, column, or diagonal. This problem has a variety of applications in fields such as artificial intelligence, backtracking algorithms, etc.
In this article, we will learn to solve the N queen problem in C using the Branch and Bound technique which is a better method as compared to simple backtracking. The backtracking Algorithm for N-Queen is already discussed here.
Example:
Input:
N = 4
Output:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
The Branch and Bound algorithm is a systematic method for solving optimization problems in computer programming. It solves the N-Queen problem efficiently after reducing the number of places we have to remove in order to check. Instead of exploring all possible positions for queens, Branch and Bound eliminates many possibilities by recognizing that placing a queen in a certain position will automatically exclude several other positions from consideration. In this way this algorithm provides us much faster and easier way to solve a problem.
Approach:
- Initialize the Board:
- Create a 2D array to represent the board.
- Initialize arrays to track columns and diagonals.
- Check Safety:
- Create a function isSafe to check if a position is safe by ensuring the current row, and both diagonals are free of other queens.
- Recursive Backtracking:
- Implement the recursive function solve that places queens column by column.
- For each column, try placing a queen in each row and check if it’s safe.
- If placing the queen is safe, mark the position and recursively try to place the next queen in the next column.
- If placing the queen is not safe, backtrack and try the next row.
- Print Solution:
- If a solution is found, print the board.
C Program to Solve N-Queen Problem
The below program implements the above approach to solve N-Queen Problem in C.
C
// C program to solve N queen problem using branch and bound
// algorithm
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int N;
// Function to print the solution board
void printSolution(int** board)
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// Print each cell of the board
printf("%d ", board[i][j]);
}
// Move to the next line after printing each row
printf("\n");
}
}
// Function to allocate memory for the 2D board
int** allocateBoard()
{
// Allocate memory for rows
int** board = (int**)malloc(N * sizeof(int*));
for (int i = 0; i < N; i++) {
// Allocate memory for columns in each row
board[i] = (int*)malloc(N * sizeof(int));
}
// Return the allocated board
return board;
}
// Function to allocate memory for a boolean array
bool* allocateBooleanArray(int size)
{
// Allocate memory for the array
bool* array = (bool*)malloc(size * sizeof(bool));
for (int i = 0; i < size; i++) {
// Initialize all elements of the array to false
array[i] = false;
}
// Return the allocated boolean array
return array;
}
// Optimized function to check if placing a queen at
// position (row, col) is safe
bool isSafe(int row, int col, bool* rows,
bool* leftDiagonals, bool* rightDiagonals)
{
if (rows[row] || leftDiagonals[row + col]
|| rightDiagonals[col - row + N - 1]) {
// If any of the row, left diagonal, or right
// diagonal is occupied, return false
return false;
}
// Otherwise, it's safe to place a queen at position
// (row, col)
return true;
}
// Recursive function to solve the N-Queen problem
bool solve(int** board, int col, bool* rows,
bool* leftDiagonals, bool* rightDiagonals)
{
if (col >= N) {
// If all queens are placed successfully, return
// true
return true;
}
// Try placing queen in each row of the current column
for (int i = 0; i < N; i++) {
if (isSafe(i, col, rows, leftDiagonals,
rightDiagonals)) {
// Mark the row and diagonals as occupied
rows[i] = true;
leftDiagonals[i + col] = true;
rightDiagonals[col - i + N - 1] = true;
// Place the queen at position (i, col)
board[i][col] = 1;
// Recur to place queens in subsequent columns
if (solve(board, col + 1, rows, leftDiagonals,
rightDiagonals)) {
// If placing queen in the next column leads
// to a solution, return true
return true;
}
// Backtrack: Unmark the row and diagonals, and
// remove the queen
rows[i] = false;
leftDiagonals[i + col] = false;
rightDiagonals[col - i + N - 1] = false;
board[i][col] = 0; // Remove the queen from
// position (i, col)
}
}
// If no position is safe in the current column, return
// false
return false;
}
int main()
{
// Taking input from the user for the size of the board
printf(
"Enter the number of rows for the square board: ");
scanf("%d", &N);
// Allocate memory for the board, and boolean arrays for
// rows and diagonals
int** board = allocateBoard();
bool* rows = allocateBooleanArray(N);
bool* leftDiagonals = allocateBooleanArray(2 * N - 1);
bool* rightDiagonals = allocateBooleanArray(2 * N - 1);
// Solve the N-Queen problem and print the solution
if (solve(board, 0, rows, leftDiagonals,
rightDiagonals)) {
printf("Solution found:\n");
// Print the board configuration
printSolution(board);
}
else {
printf("Solution does not exist\n");
}
// Free dynamically allocated memory
for (int i = 0; i < N; i++) {
free(board[i]);
}
free(board);
free(rows);
free(leftDiagonals);
free(rightDiagonals);
return 0;
}
Output
Enter the number of rows for the square board: 4
Solution found:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Time Complexity
The time complexity of the solver algorithm is (O(N!)), where (N) is the number of rows and columns in the square board. This is because for each column, the algorithm tries to place a queen in each row and then recursively tries to place the queens in the remaining columns. The number of possible combinations of queen placements in the board is (N!) since there can be only one queen in each row and each column.
Space Complexity
The space complexity of the solver algorithm is (O(N^2)), where (N) is the number of rows and columns in the square board. This is because we are using a 2D array to represent the board, which takes up (N^2) space. Additionally, we are using three boolean arrays to keep track of the occupied rows and diagonals, which take up (2N-1) space each. Therefore, the total space complexity is (O(N^2 + 6N - 3)), which is equivalent to (O(N^2)).
Similar Reads
N Queen Problem Using Branch and Bound in C++
N-Queen problem involves placing N queens on an NÃN chessboard such that no two queens threaten each other. This means no two queens share the same row, column, or diagonal. In this article, we will learn to solve the N queen problem using the Branch and Bound technique which provides an efficient m
6 min read
8 puzzle Problem using Branch and Bound in C
8-puzzle Problem is a classic sliding puzzle that consists of a 3x3 board with 8 numbered tiles and one blank space. The goal is to rearrange the tiles to match a target configuration by sliding the tiles into the blank space. The movement can be in four directions: left, right, up, and down. In thi
7 min read
Branch and Bound meaning in DSA
Branch and bound is an algorithmic technique used in computer science to solve optimization problems. Branch and bound is a systematic way of exploring all possible solutions to a problem by dividing the problem space into smaller sub-problems and then applying bounds or constraints to eliminate cer
3 min read
Which strategy can be used to solve branch and bound problem?
Branch and Bound problem can be solved using different strategies such as Least Cost (LC) Search, Breadth-First Search (BFS) and Depth-First Search (DFS). These strategies help traverse the state space tree effectively, ensuring optimal solutions. Branch and bound is a problem-solving technique used
2 min read
Why do we use branch and bound algorithm?
The Branch and Bound algorithm is used to solve optimization problems where the goal is to find the best solution out of all possible solutions. It is efficient as it eliminates the need to check all solutions by ruling out those that cannot possibly lead to the best solution. What is Branch and Bou
3 min read
Find square root of a number using Bit Manipulation
Given a non-negative integer N, the task is to find the square root of N using bitwise operations. If the integer is not the perfect square, return largest integer that is smaller than or equal to square root of N i.e., floor(âN). Examples: Input: N = 36Output: 6Explanation: The square root of 36 is
7 min read
C/C++ Program to Count set bits in an integer
Write an efficient program to count number of 1s in binary representation of an integer. Examples :Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bitsInput : n = 13Output : 3Binary representation of 11 is 1101 and has 3 set bits1. Simple Method Loop through all bits in an int
2 min read
How to count set bits in a floating point number in C?
Given a floating point number, write a function to count set bits in its binary representation. For example, floating point representation of 0.15625 has 6 set bits (See this). A typical C compiler uses single precision floating point format. We can use the idea discussed here. The idea is to take a
2 min read
Top 50 C Coding Interview Questions and Answers (2025)
C is the most popular programming language developed by Dennis Ritchie at the Bell Laboratories in 1972 to develop the UNIX operating systems. It is a general-purpose and procedural programming language. It is faster than the languages like Java and Python. C is the most used language in top compani
15+ min read
Maximum Size of an Array in C
Array in C is a collection of elements of the same data type that are stored in contiguous memory locations. The size of an array is determined by the number of elements it can store and there is a limit on this size. The maximum size of an array in C is determined by many factors, including the dat
4 min read