Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Backtracking
  • Interview Problems on Backtracking
  • MCQs on Backtracking
  • Tutorial on Backtracking
  • Backtracking vs Recursion
  • Backtracking vs Branch & Bound
  • Print Permutations
  • Subset Sum Problem
  • N-Queen Problem
  • Knight's Tour
  • Sudoku Solver
  • Rat in Maze
  • Hamiltonian Cycle
  • Graph Coloring
Open In App
Next Article:
Printing all solutions in N-Queen Problem
Next article icon

N Queen in O(n) space

Last Updated : 18 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer n, the task is to find the solution to the n-queens problem, where n 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.


Next Article
Printing all solutions in N-Queen Problem

A

Abhishek Bakare
Improve
Article Tags :
  • Algorithms
  • Backtracking
  • Matrix
  • Recursion
  • DSA
  • chessboard-problems
Practice Tags :
  • Algorithms
  • Backtracking
  • Matrix
  • Recursion

Similar Reads

    N Queen Problem
    Given an integer n, the task is to find the solution to the n-queens problem, where n 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. For example,
    15+ min read

    N-Queen in Different languages

    Java Program for N Queen Problem | Backtracking-3
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, following is the o
    4 min read
    Python Program for N Queen Problem | Backtracking-3
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix that has 1s for the blocks where queens are placed. For example, the following is th
    3 min read
    C Program for N Queen Problem | Backtracking-3
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example, the following is t
    3 min read
    4 Queens Problem
    The 4 Queens Problem consists in placing four queens on a 4 x 4 chessboard so that no two queens attack each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal. We are going to look for the solution for n=4 on a 4 x 4 chessboard in this artic
    15 min read
    8 queen problem
    Given an 8x8 chessboard, the task is to place 8 queens on the board such that no 2 queens threaten each other. Return a matrix of size 8x8, where 1 represents queen and 0 represents an empty position. Approach:The idea is to use backtracking to place the queens one by one on the board. Starting from
    9 min read
    N Queen Problem using Branch And Bound
    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. In a backtracking solut
    15+ min read
    N Queen in O(n) space
    Given an integer n, the task is to find the solution to the n-queens problem, where n 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.For example, th
    7 min read
    Printing all solutions in N-Queen Problem
    Given an integer n, the task is to find all distinct solutions to the n-queens problem, where n queens are placed on an n * n chessboard such that no two queens can attack each other. Note: Each solution is a unique configuration of n queens, represented as a permutation of [1,2,3,....,n]. The numbe
    15+ min read
    Minimum queens required to cover all the squares of a chess board
    Given the dimension of a chess board (N x M), determine the minimum number of queens required to cover all the squares of the board. A queen can attack any square along its row, column or diagonals. Examples: Input : N = 8, M = 8Output : 5Layout : Q X X X X X X X X X Q X X X X X X X X X Q X X X X Q
    14 min read
    Number of cells a queen can move with obstacles on the chessboard
    Consider a N X N chessboard with a Queen and K obstacles. The Queen cannot pass through obstacles. Given the position (x, y) of Queen, the task is to find the number of cells the queen can move. Examples: Input : N = 8, x = 4, y = 4, K = 0 Output : 27 Input : N = 8, x = 4, y = 4, K = 1, kx1 = 3, ky1
    15+ min read
    N-Queen Problem | Local Search using Hill climbing with random neighbour
    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 8 Queen problem. Input: N = 4 Output: 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 Explanation: The Position of queens are: 1 - {1, 2} 2 - {2, 4} 3 - {3,
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences