N Queen in O(n) space

Last Updated : 18 Feb, 2025

Given an integer n, the task is to find the solution to the n-queens problem, where queens are placed on an n*n chessboard such that no two queens can attack each other.

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.

N-Queen-Problem

For example, the following is a solution for the 4 Queen problem.

Solution-Of-4-Queen-Problem

Examples:

Input: n = 4
Output: [2, 4, 1, 3]
Explanation: [2, 4, 1, 3 ] and [3, 1, 4, 2] are the two possible solutions.

Input: n = 1
Output: [1]
Explanation: Only one queen can be placed in the single cell available.

Algorithm : 

The idea is to use backtracking to check all possible combinations of n queens in a chessboard of order n*n. To do so, first create an auxiliary array arr[] of size n to mark the cells occupied by queens. Start from the first row and for each row place queen at different columns and check for clashes with other queens. To check for clashes, check if any other queen is placed either in same column or same diagonal (row is not possible, as we are increasing it by 1):

  • if arr[j] == i: it means that other queen is already placed in this column.
  • if abs(arr[j] - i) == abs(j - k)): it means that other queen is already placed in this diagonal.

Implementation:

C++
// C++ Program to solve the n-queens problem

#include <bits/stdc++.h>
using namespace std;

// Function to check if it is safe to place queen
// in Kth row and Ith column.
bool isSafe(int k, int i, vector<int> &arr) {
    for(int j = 0; j < k; j++) {

        // Two in the same column
        // or in the same diagonal
        if(arr[j] == i || (abs(arr[j] - i) == abs(j - k)))
            return false; 
    }
    return true;
}

// recursive function to place queens
int placeQueens(int k, int n, vector<int> &arr) {

    // base case: if all queens are placed
    if(k == n) return 1;
    
    // try to place queen in each column
    for(int i = 1; i<=n; i++) {
        if(isSafe(k, i, arr)) {

            // place the queen
            arr.push_back(i);

            // if all the queens are placed.
            if(placeQueens(k + 1, n, arr)) return 1;

            // remove the queen to
            // initiate backtracking
            arr.pop_back();
        }
    }
    return 0;
}

vector<int> nQueen(int n) {
    
    vector<int> arr;
    if(placeQueens(0, n, arr)) return arr;
    return {-1};
}

int main() {
    int n = 4;
    vector<int> ans = nQueen(n);
    for(auto i: ans){
        cout << i << " ";
    }
    return 0;
}
Java
// Java Program to solve the n-queens problem
import java.util.*;

class GfG {
    
    // check if it is safe to place queen
    // in Kth row and Ith column.
    static boolean isSafe(int k, int i, ArrayList<Integer> arr) {
        
        for (int j = 0; j < k; j++) {
            // Two in the same column
            // or in the same diagonal
            if (arr.get(j) == i || (Math.abs(arr.get(j) - i) == Math.abs(j - k)))
                return false;
        }
        return true;
    }

    // recursive function to place queens
    static int placeQueens(int k, int n, ArrayList<Integer> arr) {
        
        // base case: if all queens are placed
        if (k == n) return 1;
        
        // try to place queen in each column
        for (int i = 1; i <= n; i++) {
            
            if (isSafe(k, i, arr)) {
                // place the queen
                arr.add(i);
                
                // if all the queens are placed.
                if (placeQueens(k + 1, n, arr) == 1)
                    return 1;
                    
                // remove the queen to
                // initiate backtracking
                arr.remove(arr.size() - 1);
            }
        }
        return 0;
    }

    static ArrayList<Integer> nQueen(int n) {
        ArrayList<Integer> arr = new ArrayList<>();
        
        if (placeQueens(0, n, arr) == 1)
            return arr;
        ArrayList<Integer> res = new ArrayList<>();
        res.add(-1);
        return res;
    }

    public static void main(String[] args) {
        int n = 4;
        ArrayList<Integer> ans = nQueen(n);
        for (int i : ans) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python Program to solve the n-queens problem

# Function to check if it is safe to place queen
# in Kth row and Ith column.
def isSafe(k, i, arr):
    for j in range(k):
        # Two in the same column
        # or in the same diagonal
        if arr[j] == i or (abs(arr[j] - i) == abs(j - k)):
            return False
    return True

# Recursive function to place queens
def placeQueens(k, n, arr):
    
    # base case: if all queens are placed
    if k == n:
        return 1
    # try to place queen in each column
    for i in range(1, n + 1):
        if isSafe(k, i, arr):
            # place the queen
            arr.append(i)
            # if all the queens are placed.
            if placeQueens(k + 1, n, arr) == 1:
                return 1
            # remove the queen to
            # initiate backtracking
            arr.pop()
    return 0

def nQueen(n):
    arr = []
    if placeQueens(0, n, arr) == 1:
        return arr
    return [-1]

if __name__ == "__main__":
    n = 4
    ans = nQueen(n)
    for i in ans:
        print(i, end=" ")
C#
// C# Program to solve the n-queens problem

using System;
using System.Collections.Generic;

class GfG {
    
    // Functiont to check if it is safe to place queen
    // in Kth row and Ith column.
    static bool IsSafe(int k, int i, List<int> arr) {
        for (int j = 0; j < k; j++) {
            // Two in the same column
            // or in the same diagonal
            if (arr[j] == i || (Math.Abs(arr[j] - i) == Math.Abs(j - k)))
                return false;
        }
        return true;
    }

    // recursive function to place queens
    static int PlaceQueens(int k, int n, List<int> arr) {
        // base case: if all queens are placed
        if (k == n) return 1;
        
        // try to place queen in each column
        for (int i = 1; i <= n; i++) {
            if (IsSafe(k, i, arr)) {
                // place the queen
                arr.Add(i);
                // if all the queens are placed.
                if (PlaceQueens(k + 1, n, arr) == 1)
                    return 1;
                // remove the queen to
                // initiate backtracking
                arr.RemoveAt(arr.Count - 1);
            }
        }
        return 0;
    }

    static List<int> NQueen(int n) {
        List<int> arr = new List<int>();
        if (PlaceQueens(0, n, arr) == 1)
            return arr;
        return new List<int> { -1 };
    }

    static void Main() {
        int n = 4;
        List<int> ans = NQueen(n);
        foreach (int i in ans) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// JavaScript program to solve the n-queens problem

// Function to check if it is safe to place queen
// in Kth row and Ith column.
function isSafe(k, i, arr) {
    for (let j = 0; j < k; j++) {
        // Two in the same column
        // or in the same diagonal
        if (arr[j] === i || (Math.abs(arr[j] - i) === Math.abs(j - k)))
            return false;
    }
    return true;
}

// recursive function to place queens
function placeQueens(k, n, arr) {
    // base case: if all queens are placed
    if (k === n) return 1;
    
    // try to place queen in each column
    for (let i = 1; i <= n; i++) {
        if (isSafe(k, i, arr)) {
            // place the queen
            arr.push(i);
            // if all the queens are placed.
            if (placeQueens(k + 1, n, arr) === 1)
                return 1;
            // remove the queen to
            // initiate backtracking
            arr.pop();
        }
    }
    return 0;
}

function nQueen(n) {
    let arr = [];
    if (placeQueens(0, n, arr) === 1)
        return arr;
    return [-1];
}

// Driver Code
let n = 4;
let ans = nQueen(n);
console.log(ans.join(" "));

Output
2 4 1 3 

Time Complexity: O(n!), because in the worst case scenario, every queen must be tried in every column of every row.
Space Complexity: O(n), an array of maximum possible size of n is used to store the column index.

Comment