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: 4
Output: [2, 4, 1, 3]
Explanation: [2, 4, 1, 3 ] and [3, 1, 4, 2] are the two possible solutions.
Input: 1
Output: [1]
Explanation: Only one queen can be placed in the single cell available.
[Naive Approach] - Using Backtracking - O(n*n!) Time and O(n*n) Space
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 matrix mat[][] of order n*n to mark the cellsoccupied 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, iterate through all the rows of current column and both the diagonals. If it is safe to place queen in current column, mark the cell occupied in matrix mat[][] and move to the next row. If at any row, there is no safe column to place the queen, backtrack to previous row and place the queen in other safe column and again check for the next row.
Below given is the recursive tree of the above approach:
Recursive tree for N Queen problemBelow given is the 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
// the queen at board[row][col]
int isSafe(vector<vector<int>>& mat,
int row, int col) {
int n = mat.size();
int i, j;
// Check this col on upper side
for (i = 0; i < row; i++)
if (mat[i][col])
return 0;
// Check upper diagonal on left side
for (i = row-1, j = col-1; i >= 0 &&
j >= 0; i--, j--)
if (mat[i][j])
return 0;
// Check upper diagonal on right side
for (i = row-1, j = col+1; j < n &&
i >= 0; i--, j++)
if (mat[i][j])
return 0;
return 1;
}
int placeQueens(int row, vector<vector<int>>& mat) {
int n = mat.size();
// base case: If all queens are placed
// then return true
if(row == n) return 1;
// Consider the row and try placing
// queen in all columns one by one
for(int i = 0; i < n; i++){
// Check if the queen can be placed
if(isSafe(mat, row, i)){
mat[row][i] = 1;
if(placeQueens(row + 1, mat))
return 1;
mat[row][i] = 0;
}
}
return 0;
}
// Function to find the solution
// to the N-Queens problem
vector<int> nQueen(int n) {
// Initialize the board
vector<vector<int>> mat(n, vector<int>(n, 0));
// If the solution exists
if(placeQueens(0, mat)){
// to store the columns of the queens
vector<int> ans;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(mat[i][j]){
ans.push_back(j + 1);
}
}
}
return ans;
}
else 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 {
// Function to check if it is safe to place
// the queen at board[row][col]
static boolean isSafe(int[][] mat,
int row, int col) {
int n = mat.length;
// Check this col on upper side
for (int i = 0; i < row; i++)
if (mat[i][col] == 1)
return false;
// Check upper diagonal on left side
for (int i = row - 1, j = col - 1;
i >= 0 && j >= 0; i--, j--)
if (mat[i][j] == 1)
return false;
// Check upper diagonal on right side
for (int i = row - 1, j = col + 1;
j < n && i >= 0; i--, j++)
if (mat[i][j] == 1)
return false;
return true;
}
static boolean placeQueens(int row, int[][] mat) {
int n = mat.length;
// base case: If all queens are placed
// then return true
if (row == n)
return true;
// Consider the row and try placing
// queen in all columns one by one
for (int i = 0; i < n; i++) {
// Check if the queen can be placed
if (isSafe(mat, row, i)) {
mat[row][i] = 1;
if (placeQueens(row + 1, mat))
return true;
mat[row][i] = 0;
}
}
return false;
}
// Function to find the solution
// to the N-Queens problem
static List<Integer> nQueen(int n) {
// Initialize the board
int[][] mat = new int[n][n];
// If the solution exists
if (placeQueens(0, mat)) {
// to store the columns of the queens
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
ans.add(j + 1);
}
}
}
return ans;
}
else
return Collections.singletonList(-1);
}
public static void main(String[] args) {
int n = 4;
List<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
# the queen at board[row][col]
def isSafe(mat, row, col):
n = len(mat)
# Check this col on upper side
for i in range(row):
if mat[i][col]:
return False
# Check upper diagonal on left side
for i, j in zip(range(row - 1, -1, -1),
range(col - 1, -1, -1)):
if mat[i][j]:
return False
# Check upper diagonal on right side
for i, j in zip(range(row - 1, -1, -1),
range(col + 1, n)):
if mat[i][j]:
return False
return True
def placeQueens(row, mat):
n = len(mat)
# If all queens are placed
# then return true
if row == n:
return True
# Consider the row and try placing
# queen in all columns one by one
for i in range(n):
# Check if the queen can be placed
if isSafe(mat, row, i):
mat[row][i] = 1
if placeQueens(row + 1, mat):
return True
mat[row][i] = 0
return False
# Function to find the solution
# to the N-Queens problem
def nQueen(n):
# Initialize the board
mat = [[0 for _ in range(n)] for _ in range(n)]
# If the solution exists
if placeQueens(0, mat):
# to store the columns of the queens
ans = []
for i in range(n):
for j in range(n):
if mat[i][j]:
ans.append(j + 1)
return ans
else:
return [-1]
if __name__ == "__main__":
n = 4
ans = nQueen(n)
print(" ".join(map(str, ans)))
C#
// C# Program to solve the n-queens problem
using System;
using System.Collections.Generic;
class GfG {
// Function to check if it is safe to place
// the queen at board[row][col]
static bool IsSafe(int[,] mat,
int row, int col) {
int n = mat.GetLength(0);
// Check this col on upper side
for (int i = 0; i < row; i++)
if (mat[i, col] == 1)
return false;
// Check upper diagonal on left side
for (int i = row - 1, j = col - 1;
i >= 0 && j >= 0; i--, j--)
if (mat[i, j] == 1)
return false;
// Check upper diagonal on right side
for (int i = row - 1, j = col + 1;
j < n && i >= 0; i--, j++)
if (mat[i, j] == 1)
return false;
return true;
}
static bool PlaceQueens(int row, int[,] mat) {
int n = mat.GetLength(0);
// base case: If all queens are placed
// then return true
if (row == n)
return true;
// Consider the row and try placing
// queen in all columns one by one
for (int i = 0; i < n; i++) {
// Check if the queen can be placed
if (IsSafe(mat, row, i)) {
mat[row, i] = 1;
if (PlaceQueens(row + 1, mat))
return true;
mat[row, i] = 0;
}
}
return false;
}
// Function to find the solution
// to the N-Queens problem
public static List<int> NQueen(int n) {
// Initialize the board
int[,] mat = new int[n, n];
// If the solution exists
if (PlaceQueens(0, mat)) {
// to store the columns of the queens
List<int> ans = new List<int>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (mat[i, j] == 1) {
ans.Add(j + 1);
}
}
}
return ans;
} else
return new List<int> { -1 };
}
static void Main(string[] args) {
int n = 4;
List<int> ans = NQueen(n);
Console.WriteLine(string.Join(" ", ans));
}
}
JavaScript
// JavaScript Program to solve the n-queens problem
// Function to check if it is safe to place
// the queen at board[row][col]
function isSafe(mat, row, col) {
const n = mat.length;
// Check this col on upper side
for (let i = 0; i < row; i++)
if (mat[i][col] === 1)
return false;
// Check upper diagonal on left side
for (let i = row - 1, j = col - 1;
i >= 0 && j >= 0; i--, j--)
if (mat[i][j] === 1)
return false;
// Check upper diagonal on right side
for (let i = row - 1, j = col + 1;
j < n && i >= 0; i--, j++)
if (mat[i][j] === 1)
return false;
return true;
}
function placeQueens(row, mat) {
const n = mat.length;
// base case: If all queens are placed
// then return true
if (row === n)
return true;
// Consider the row and try placing
// queen in all columns one by one
for (let i = 0; i < n; i++) {
// Check if the queen can be placed
if (isSafe(mat, row, i)) {
mat[row][i] = 1;
if (placeQueens(row + 1, mat))
return true;
mat[row][i] = 0;
}
}
return false;
}
// Function to find the solution
// to the N-Queens problem
function nQueen(n) {
// Initialize the board
const mat = Array.from({ length: n },
() => Array(n).fill(0));
// If the solution exists
if (placeQueens(0, mat)) {
// to store the columns of the queens
const ans = [];
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (mat[i][j] === 1) {
ans.push(j + 1);
}
}
}
return ans;
} else
return [-1];
}
const n = 4;
const ans = nQueen(n);
console.log(ans.join(" "));
Time Complexity: O(n*n!)
Auxiliary Space: O(n2)
[Optimized Approach] - O(n!) Time and O(n) Space
The above approach can be optimized by reducing the time required to check for clashes using isSafe() function. The idea is not to check every element in both the diagonals, instead use the property of diagonals:
- The sum of i and j is constant and unique for each right diagonal, where i is the row of elements and j is the column of elements.
- The difference between i and j is constant and unique for each left diagonal, where i and j are row and column of element respectively.
To do so, create three arrays cols[], rightDiagonal[] and leftDiagonal[] to mark the index of columns, left diagonal and right diagonals occupied by queens. For any cell, if all three arrays have value 0, we can place the queen at that cell.
Below is the implementation:
C++
// C++ Program to solve the n-queens problem
#include <bits/stdc++.h>
using namespace std;
int placeQueens(int i, vector<int> &cols, vector<int> &leftDiagonal,
vector<int> &rightDiagonal, vector<int> &cur) {
int n = cols.size();
// base case: If all queens are placed
// then return true
if(i == n) return 1;
// Consider the row and try placing
// queen in all columns one by one
for(int j = 0; j < n; j++){
// Check if the queen can be placed
if(cols[j] || rightDiagonal[i + j] ||
leftDiagonal[i - j + n - 1])
continue;
// mark the cell occupied
cols[j] = 1;
rightDiagonal[i+j] = 1;
leftDiagonal[i - j + n - 1] = 1;
cur.push_back(j+1);
if(placeQueens(i + 1, cols, leftDiagonal, rightDiagonal, cur))
return 1;
// remove the queen from current cell
cur.pop_back();
cols[j] = 0;
rightDiagonal[i+j] = 0;
leftDiagonal[i - j + n - 1] = 0;
}
return 0;
}
// Function to find the solution
// to the N-Queens problem
vector<int> nQueen(int n) {
// array to mark the occupied cells
vector<int> cols(n, 0);
vector<int> leftDiagonal(n*2, 0);
vector<int> rightDiagonal(n*2, 0);
vector<int> cur;
// If the solution exists
if(placeQueens(0, cols, leftDiagonal, rightDiagonal, cur))
return cur;
else 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 {
static boolean placeQueens(int i, int[] cols, int[] leftDiagonal,
int[] rightDiagonal, List<Integer> cur) {
int n = cols.length;
// base case: If all queens are placed
// then return true
if (i == n) return true;
// Consider the row and try placing
// queen in all columns one by one
for (int j = 0; j < n; j++) {
// Check if the queen can be placed
if (cols[j] == 1 || rightDiagonal[i + j] == 1 ||
leftDiagonal[i - j + n - 1] == 1)
continue;
// mark the cell occupied
cols[j] = 1;
rightDiagonal[i + j] = 1;
leftDiagonal[i - j + n - 1] = 1;
cur.add(j + 1);
if (placeQueens(i + 1, cols, leftDiagonal,
rightDiagonal, cur))
return true;
// remove the queen from current cell
cur.remove(cur.size() - 1);
cols[j] = 0;
rightDiagonal[i + j] = 0;
leftDiagonal[i - j + n - 1] = 0;
}
return false;
}
// Function to find the solution
// to the N-Queens problem
static List<Integer> nQueen(int n) {
// array to mark the occupied cells
int[] cols = new int[n];
int[] leftDiagonal = new int[n * 2];
int[] rightDiagonal = new int[n * 2];
List<Integer> cur = new ArrayList<>();
// If the solution exists
if (placeQueens(0, cols, leftDiagonal,
rightDiagonal, cur))
return cur;
else return Collections.singletonList(-1);
}
public static void main(String[] args) {
int n = 4;
List<Integer> ans = nQueen(n);
for (int i : ans) {
System.out.print(i + " ");
}
}
}
Python
# Python Program to solve the n-queens problem
def placeQueens(i, cols, leftDiagonal, rightDiagonal, cur):
n = len(cols)
# base case: If all queens are placed
# then return true
if i == n:
return True
# Consider the row and try placing
# queen in all columns one by one
for j in range(n):
# Check if the queen can be placed
if cols[j] or rightDiagonal[i + j] or leftDiagonal[i - j + n - 1]:
continue
# mark the cell occupied
cols[j] = 1
rightDiagonal[i + j] = 1
leftDiagonal[i - j + n - 1] = 1
cur.append(j + 1)
if placeQueens(i + 1, cols, leftDiagonal, rightDiagonal, cur):
return True
# remove the queen from current cell
cur.pop()
cols[j] = 0
rightDiagonal[i + j] = 0
leftDiagonal[i - j + n - 1] = 0
return False
# Function to find the solution
# to the N-Queens problem
def nQueen(n):
# array to mark the occupied cells
cols = [0] * n
leftDiagonal = [0] * (n * 2)
rightDiagonal = [0] * (n * 2)
cur = []
# If the solution exists
if placeQueens(0, cols, leftDiagonal, rightDiagonal, cur):
return cur
else:
return [-1]
if __name__ == "__main__":
n = 4
ans = nQueen(n)
print(" ".join(map(str, ans)))
C#
// C# Program to solve the n-queens problem
using System;
using System.Collections.Generic;
class GfG {
static bool PlaceQueens(int i, int[] cols, int[] leftDiagonal,
int[] rightDiagonal, List<int> cur) {
int n = cols.Length;
// base case: If all queens are placed
// then return true
if (i == n) return true;
// Consider the row and try placing
// queen in all columns one by one
for (int j = 0; j < n; j++) {
// Check if the queen can be placed
if (cols[j] == 1 || rightDiagonal[i + j] == 1 ||
leftDiagonal[i - j + n - 1] == 1)
continue;
// mark the cell occupied
cols[j] = 1;
rightDiagonal[i + j] = 1;
leftDiagonal[i - j + n - 1] = 1;
cur.Add(j + 1);
if (PlaceQueens(i + 1, cols, leftDiagonal,
rightDiagonal, cur))
return true;
// remove the queen from current cell
cur.RemoveAt(cur.Count - 1);
cols[j] = 0;
rightDiagonal[i + j] = 0;
leftDiagonal[i - j + n - 1] = 0;
}
return false;
}
// Function to find the solution
// to the N-Queens problem
static List<int> NQueen(int n) {
// array to mark the occupied cells
int[] cols = new int[n];
int[] leftDiagonal = new int[n * 2];
int[] rightDiagonal = new int[n * 2];
List<int> cur = new List<int>();
// If the solution exists
if (PlaceQueens(0, cols, leftDiagonal,
rightDiagonal, cur))
return cur;
else return new List<int> { -1 };
}
static void Main(string[] args) {
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 placeQueens(i, cols, leftDiagonal, rightDiagonal, cur) {
const n = cols.length;
// base case: If all queens are placed
// then return true
if (i === n) return true;
// Consider the row and try placing
// queen in all columns one by one
for (let j = 0; j < n; j++) {
// Check if the queen can be placed
if (cols[j] || rightDiagonal[i + j] ||
leftDiagonal[i - j + n - 1])
continue;
// mark the cell occupied
cols[j] = 1;
rightDiagonal[i + j] = 1;
leftDiagonal[i - j + n - 1] = 1;
cur.push(j + 1);
if (placeQueens(i + 1, cols, leftDiagonal,
rightDiagonal, cur))
return true;
// remove the queen from current cell
cur.pop();
cols[j] = 0;
rightDiagonal[i + j] = 0;
leftDiagonal[i - j + n - 1] = 0;
}
return false;
}
// Function to find the solution
// to the N-Queens problem
function nQueen(n) {
// array to mark the occupied cells
const cols = new Array(n).fill(0);
const leftDiagonal = new Array(n * 2).fill(0);
const rightDiagonal = new Array(n * 2).fill(0);
const cur = [];
// If the solution exists
if (placeQueens(0, cols, leftDiagonal,
rightDiagonal, cur))
return cur;
else return [-1];
}
const n = 4;
const ans = nQueen(n);
console.log(ans.join(" "));
Time Complexity: O(n!)
Auxiliary Space: O(n)
Related Articles:
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem