N-Queens Problem Solved Using C: Tutorial and Code

This C program can solve the n-queen problem.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
void printSolution(int **board, int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            printf("%s ", board[i][j] ? "Q" : "#");
        }
        printf("\n\n");
    }
}
bool isSafe(int **board, int n, int row, int col)
{
    int i, j;
    for (i = 0; i < col; i++)
    {
        if (board[row][i])
        {
            return false;
        }
    }
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
    {
        if (board[i][j])
        {
            return false;
        }
    }
    for (i = row, j = col; j >= 0 && i < n; i++, j--)
    {
        if (board[i][j])
        {
            return false;
        }
    }
    return true;
}
bool solveNQUtil(int **board, int n, int col)
{
    if (col >= n)
    {
        return true;
    }
    for (int i = 0; i < n; i++)
    {
        if (isSafe(board, n, i, col))
        {
            board[i][col] = 1;
            if (solveNQUtil(board, n, col + 1))
            {
                return true;
            }
            board[i][col] = 0;
        }
    }
    return false;
}
bool solveNQ(int n)
{
    int **board = (int **)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++)
    {
        board[i] = (int *)malloc(n * sizeof(int));
        for (int j = 0; j < n; j++)
        {
            board[i][j] = 0;
        }
    }
    if (!solveNQUtil(board, n, 0))
    {
        printf("Solution does not exist\n");
        for (int i = 0; i < n; i++)
        {
            free(board[i]);
        }
        free(board);
        return false;
    }
    printSolution(board, n);
    for (int i = 0; i < n; i++)
    {
        free(board[i]);
    }
    free(board);
    return true;
}
int main()
{
    int n;
    printf("Enter the number of queens: ");
    scanf(" %d", &n);
    printf("\n");
    solveNQ(n);
    getch();
    return 0;
}
Enter the number of queens: 4

# # Q # 

Q # # # 

# # # Q 

# Q # #
0
Subscribe to my newsletter

Read articles from PRATHAM N GUNDIKERE directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

PRATHAM N GUNDIKERE
PRATHAM N GUNDIKERE

Native Android Developer