# Printing all solutions in N-Queen Problem

• Difficulty Level : Hard
• Last Updated : 07 Jul, 2022

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, following is a solution for 4 Queen problem.

In previous post, we have discussed an approach that prints only one possible solution, so now in this post, the task is to print all solutions in N-Queen Problem. Each solution contains distinct board configurations of the N-queens’ placement, where the solutions are a permutation of [1,2,3..n] in increasing order, here the number in the ith place denotes that the ith-column queen is placed in the row with that number. For the example above solution is written as [[2 4 1 3 ] [3 1 4 2 ]]. The solution discussed here is an extension of the same approach.

Recommended Practice

Backtracking Algorithm

The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false.

1) Start in the leftmost column
2) If all queens are placed
return true
3) Try all rows in the current column.  Do following
for every tried row.
a) If the queen can be placed safely in this row
then mark this [row, column] as part of the
solution and recursively check if placing
queen here leads to a solution.
b) If placing queen in [row, column] leads to a
solution then return true.
c) If placing queen doesn't lead to a solution
then unmark this [row, column] (Backtrack)
and go to step (a) to try other rows.
3) If all rows have been tried and nothing worked,
return false to trigger backtracking.

A modification is that we can find whether we have a previously placed queen in a column or in left diagonal or in right diagonal in O(1) time. We can observe that

1. For all cells in a particular left diagonal , their row + col  = constant.
2. For all cells in a particular right diagonal, their row – col + n – 1 = constant.

Let say n = 5, then we have a total of 2n-1 left and right diagonals

Let say we placed a queen at (2,0)

(2,0) have leftDiagonal value = 2. Now we can not place another queen at (1,1) and (0,2) because both of these have same leftDiagonal value as for (2,0). Similar thing can be noticed for right diagonal as well.

Implementation:

## C++

 /* C/C++ program to solve N Queen Problem usingbacktracking */#include using namespace std; vector > result; /* A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when "col" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens */bool isSafe(vector > board,            int row, int col){    int i, j;    int N = board.size();     /* Check this row on left side */    for (i = 0; i < col; i++)        if (board[row][i])            return false;     /* Check upper diagonal on left side */    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)        if (board[i][j])            return false;     /* Check lower diagonal on left side */    for (i = row, j = col; j >= 0 && i < N; i++, j--)        if (board[i][j])            return false;     return true;} /* A recursive utility function to solve NQueen problem */bool solveNQUtil(vector >& board, int col){    /* base case: If all queens are placed    then return true */    int N = board.size();    if (col == N) {        vector v;        for (int i = 0; i < N; i++) {            for (int j = 0; j < N; j++) {                if (board[i][j] == 1)                    v.push_back(j + 1);            }        }        result.push_back(v);        return true;    }     /* Consider this column and try placing    this queen in all rows one by one */    bool res = false;    for (int i = 0; i < N; i++) {        /* Check if queen can be placed on        board[i][col] */        if (isSafe(board, i, col)) {            /* Place this queen in board[i][col] */            board[i][col] = 1;             // Make result true if any placement            // is possible            res = solveNQUtil(board, col + 1) || res;             /* If placing queen in board[i][col]            doesn't lead to a solution, then            remove queen from board[i][col] */            board[i][col] = 0; // BACKTRACK        }    }     /* If queen can not be place in any row in        this column col then return false */    return res;} /* This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.*/ vector > nQueen(int n){    result.clear();    vector > board(n, vector(n, 0));     if (solveNQUtil(board, 0) == false) {        return {};    }     sort(result.begin(), result.end());    return result;} // Driver Codeint main(){    int n = 4;    vector > v = nQueen(n);     for (auto ar : v) {        cout << "[";        for (auto it : ar)            cout << it << " ";        cout << "]";    }     return 0;}

## Java

 /* Java program to solve N QueenProblem using backtracking */import java.util.*;class GfG {    /* This function solves the N Queen problem using    Backtracking. It mainly uses solveNQUtil() to    solve the problem.    */    static List> nQueen(int n) {       // cols[i] = true if there is a queen previously placed at ith column        cols = new boolean[n];        // leftDiagonal[i] = true if there is a queen previously placed at          // i = (row + col )th left diagonal        leftDiagonal = new boolean[2*n];          // rightDiagonal[i] = true if there is a queen previously placed at          // i = (row - col + n - 1)th rightDiagonal diagonal        rightDiagonal = new boolean[2*n];        result  = new ArrayList<>();        List temp = new ArrayList<>();        for(int i=0;i> result,int n,int row,List comb){        if(row==n){          // if row==n it means we have successfully placed all n queens.          // hence add current arrangement to our answer          // comb represent current combination            result.add(new ArrayList<>(comb));            return;        }        for(int col = 0;col > result        = new ArrayList >();   static boolean[] cols,leftDiagonal,rightDiagonal;     // Driver code    public static void main(String[] args)    {        int n = 4;         List > res = nQueen(n);        System.out.println(res);    }}

## Python3

 ''' Python3 program to solve N Queen Problem usingbacktracking '''  result = [] # A utility function to print solution  ''' A utility function to check if a queen canbe placed on board[row][col]. Note that thisfunction is called when "col" queens arealready placed in columns from 0 to col -1.So we need to check only left side forattacking queens '''  def isSafe(board, row, col):     # Check this row on left side    for i in range(col):        if (board[row][i]):            return False     # Check upper diagonal on left side    i = row    j = col    while i >= 0 and j >= 0:        if(board[i][j]):            return False        i -= 1        j -= 1     # Check lower diagonal on left side    i = row    j = col    while j >= 0 and i < 4:        if(board[i][j]):            return False        i = i + 1        j = j - 1     return True  ''' A recursive utility function to solve NQueen problem '''  def solveNQUtil(board, col):    ''' base case: If all queens are placed    then return true '''    if (col == 4):        v = []        for i in board:          for j in range(len(i)):            if i[j] == 1:              v.append(j+1)        result.append(v)        return True     ''' Consider this column and try placing    this queen in all rows one by one '''    res = False    for i in range(4):         ''' Check if queen can be placed on        board[i][col] '''        if (isSafe(board, i, col)):             # Place this queen in board[i][col]            board[i][col] = 1             # Make result true if any placement            # is possible            res = solveNQUtil(board, col + 1) or res             ''' If placing queen in board[i][col]            doesn't lead to a solution, then            remove queen from board[i][col] '''            board[i][col] = 0  # BACKTRACK     ''' If queen can not be place in any row in        this column col then return false '''    return res  ''' This function solves the N Queen problem usingBacktracking. It mainly uses solveNQUtil() tosolve the problem. It returns false if queenscannot be placed, otherwise return true andprints placement of queens in the form of 1s.Please note that there may be more than onesolutions, this function prints one of thefeasible solutions.'''  def solveNQ(n):    result.clear()    board = [[0 for j in range(n)]             for i in range(n)]    solveNQUtil(board, 0)    result.sort()    return result  # Driver Coden = 4res = solveNQ(n)print(res) # This code is contributed by YatinGupta

## C#

 /* C# program to solve N QueenProblem using backtracking */using System;using System.Collections;using System.Collections.Generic; class GfG {     static List > result = new List >();     /* A utility function to check if a queen can    be placed on board[row,col]. Note that this    function is called when "col" queens are    already placed in columns from 0 to col -1.    So we need to check only left side for    attacking queens */    static bool isSafe(int[, ] board, int row, int col,                       int N)    {        int i, j;         /* Check this row on left side */        for (i = 0; i < col; i++)            if (board[row, i] == 1)                return false;         /* Check upper diagonal on left side */        for (i = row, j = col; i >= 0 && j >= 0; i--, j--)            if (board[i, j] == 1)                return false;         /* Check lower diagonal on left side */        for (i = row, j = col; j >= 0 && i < N; i++, j--)            if (board[i, j] == 1)                return false;         return true;    }     /* A recursive utility function    to solve N Queen problem */    static bool solveNQUtil(int[, ] board, int col, int N)    {        /* base case: If all queens are placed        then return true */         if (col == N) {            List v = new List();            for (int i = 0; i < N; i++)                for (int j = 0; j < N; j++) {                    if (board[i, j] == 1)                        v.Add(j + 1);                }            result.Add(v);            return true;        }         /* Consider this column and try placing        this queen in all rows one by one */        bool res = false;        for (int i = 0; i < N; i++) {            /* Check if queen can be placed on            board[i,col] */            if (isSafe(board, i, col, N)) {                /* Place this queen in board[i,col] */                board[i, col] = 1;                 // Make result true if any placement                // is possible                res = solveNQUtil(board, col + 1, N) || res;                 /* If placing queen in board[i,col]                doesn't lead to a solution, then                remove queen from board[i,col] */                board[i, col] = 0; // BACKTRACK            }        }         /* If queen can not be place in any row in            this column col then return false */        return res;    }     /* This function solves the N Queen problem using    Backtracking. It mainly uses solveNQUtil() to    solve the problem. It returns false if queens    cannot be placed, otherwise return true and    prints placement of queens in the form of 1s.    Please note that there may be more than one    solutions, this function prints one of the    feasible solutions.*/    static List > solveNQ(int n)    {        result.Clear();        int[, ] board = new int[n, n];         solveNQUtil(board, 0, n);        return result;    }     // Driver code    public static void Main()    {        int n = 4;        List > res = solveNQ(n);        for (int i = 0; i < res.Count; i++) {            Console.Write("[");            for (int j = 0; j < res[i].Count; j++) {                Console.Write(res[i][j]+ " ");            }            Console.Write("]");        }    }} /* This code contributed by PrinciRaj1992 */

Output

[2 4 1 3 ][3 1 4 2 ]

Algorithm:
There is always only one queen in each row and each column, so idea of backtracking is to start placing queen from the leftmost column of each row and find a column where the queen could be placed without collision with previously placed queens. It is repeated from the first row till the last row. While placing a queen, it is tracked as if it is not making a collision (row-wise, column-wise and diagonally) with queens placed in previous rows. Once it is found that the queen can’t be placed at a particular column index in a row, the algorithm backtracks and change the position of the queen placed in the previous row then moves forward to place the queen in the next row.

1. Start with three-bit vector which is used to track safe place for queen placement row-wise, column-wise and diagonally in each iteration.
2. Three-bit vector will contain information as bellow:
• rowmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row.
• ldmask: set bit index (i) of this bit vector will indicate, the queen can’t e placed at ith column of next row. It represents the unsafe column index for next row falls under left diagonal of queens placed in previous rows.
• rdmask: set bit index (i) of this bit vector will indicate, the queen can’t be placed at ith column of next row. It represents the unsafe column index for next row falls right diagonal of queens placed in previous rows.
3. There is a 2-D (NxN) matrix (board), which will have ‘ ‘ character at all indexes in beginning and it gets filled by ‘Q’ row-by-row. Once all rows are filled by ‘Q’, the current solution is pushed into the result list.

Below is the implementation of the above approach: