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, the following is a solution for the 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(" "));
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.
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
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