N-Queens Problem in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
int N=4, board[4], sol=0;
int safe(int r, int c) {
    for(int i=0; i<r; i++)
        if(board[i]==c || abs(board[i]-c)==r-i) return 0;
    return 1;
}
void solve(int r) {
    if(r==N) {
        for(int i=0;i<N;i++,puts(""))
            for(int j=0;j<N;j++) printf("%c ", board[i]==j ? 'Q' : '.');
        puts(""); sol++; return;
    }
    for(int c=0;c<N;c++)
        if(safe(r,c)) { board[r]=c; solve(r+1); }
}
int main() {
    solve(0);
    printf("Total Solutions: %d", sol);
}

C Output

Input:  

N = 4

Output: . Q . . . . . Q Q . . . . . Q . . . Q . Q . . . . . . Q . Q . . Total Solutions: 2


C++ Program

#include <iostream>
#include <cmath>
using namespace std;
int N=5, board[5], sol=0;
bool safe(int r, int c) {
    for(int i=0;i<r;i++)
        if(board[i]==c || abs(board[i]-c)==r-i) return false;
    return true;
}
void solve(int r) {
    if(r==N) {
        for(int i=0;i<N;i++,cout<<endl)
            for(int j=0;j<N;j++) cout<<(board[i]==j?"Q ":" .");
        cout<<endl; sol++; return;
    }
    for(int c=0;c<N;c++)
        if(safe(r,c)) { board[r]=c; solve(r+1); }
}
int main() {
    solve(0);
    cout << "Total Solutions: " << sol;
}

C++ Output

Input:  

N = 5

Output: Q . . . . . . Q . . . . . . Q . Q . . . . . . Q . ... Total Solutions: 10


JAVA Program

public class Main {
    static int N = 4, sol = 0;
    static int[] board = new int[N];
    static boolean isSafe(int r, int c) {
        for(int i=0;i<r;i++)
            if(board[i]==c || Math.abs(board[i]-c)==r-i) return false;
        return true;
    }
    static void solve(int r) {
        if(r==N){
            for(int i=0;i<N;i++) {
                for(int j=0;j<N;j++)
                    System.out.print(board[i]==j?"Q ":" .");
                System.out.println();
            }
            System.out.println();
            sol++; return;
        }
        for(int c=0;c<N;c++)
            if(isSafe(r,c)){ board[r]=c; solve(r+1); }
    }
    public static void main(String[] args) {
        solve(0);
        System.out.println("Total Solutions: " + sol);
    }
}

JAVA Output

Input:  

N = 4

Output: . Q . . . . . Q Q . . . . . Q . . . Q . Q . . . . . . Q . Q . . Total Solutions: 2


Python Program

N = 4
board = [0]*N
sol = 0
def is_safe(r, c):
    for i in range(r):
        if board[i]==c or abs(board[i]-c)==r-i: return False
    return True
def solve(r):
    global sol
    if r == N:
        for i in range(N):
            print(' '.join('Q' if board[i]==j else '.' for j in range(N)))
        print(); sol += 1; return
    for c in range(N):
        if is_safe(r,c): board[r]=c; solve(r+1)
solve(0)
print("Total Solutions:", sol)

Python Output

Input:  

N = 4

Output: . Q . . . . . Q Q . . . . . Q . . . Q . Q . . . . . . Q . Q . . Total Solutions: 2


In-Depth Explanation
Example
In the 4×4 board, there are two correct solutions in which no queens attack one another. Each queen is so placed that they do not share the same row, column, or diagonal. To illustrate, putting a queen at (0,1) puts pressure on the subsequent placement not to position any queen on the diagonal lines starting from that square.

Real-Life Analogy
Think of having a high-security meeting where every speaker (queen) has to be placed on a square such that no other speaker can see or hear them — neither vertically, horizontally, nor diagonally. You have to allocate the chairs (board cells) so that there is no conflict whatsoever, and it is an actual planning and conflict-resolution simulation.

Why It Matters
The N-Queens problem imparts:

Backtracking, an essential idea in constraint satisfaction

Effective row-column-diagonal checking

Pruning invalid states early

Designing recursive algorithms with neat exit conditions

It simulates systems in the real world in which objects need to be uniquely assigned (such as server assignment, frequency assignment, exam timetabling, or even airline seating).

Learning Insights
Solving N-Queens improves your insight into:

How recursive depth works

How to verify constraints along the traversal

Debugging recursive solutions

How backtracking unravels on incorrect paths and investigates alternatives

It refines the mental model of recursion, which is central to being a good programmer.

Interview Use
Commonly asked in coding interviews, the N-Queens problem:

Verifies backtracking knowledge

Illustrates recursion depth management

Illustrates how to optimize with constraints

It's utilized in interviews at Google, Amazon, Facebook, and Microsoft to test for clean problem solving with constraints.

N-Queens problem is a foundation of algorithmic thought, particularly in recursion and backtracking. Through understanding this problem, you gain insight into deeper aspects of constraint-based decision-making, recursion stack behavior, and how to craft efficient search algorithms. It's extremely useful in interviews and actual planning systems. With shortest conceivable solutions in C, C++, Java, and Python, this tutorial enables students and professionals to approach constraint satisfaction problems with confidence and elegant, logical code.