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.
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 are two solutions 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. The solution discussed here is an extension of same approach.
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.
There is only a slight modification in above algorithm that is highlighted in the code.
C++
/* C/C++ program to solve N Queen Problem using backtracking */#include<bits/stdc++.h> #define N 4 /* A utility function to print solution */void printSolution(int board[N][N]) { static int k = 1; printf("%d-\n",k++); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", board[i][j]); printf("\n"); } printf("\n"); } /* 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 */bool isSafe(int board[N][N], int row, int col) { int i, j; /* 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 N Queen problem */bool solveNQUtil(int board[N][N], int col) { /* base case: If all queens are placed then return true */ if (col == N) { printSolution(board); 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 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.*/void solveNQ() { int board[N][N]; memset(board, 0, sizeof(board)); if (solveNQUtil(board, 0) == false) { printf("Solution does not exist"); return ; } return ; } // driver program to test above function int main() { solveNQ(); return 0; } |
Java
/* Java program to solve N Queen Problem using backtracking */ class GfG { static int N = 4; static int k = 1; /* A utility function to print solution */static void printSolution(int board[][]) { System.out.printf("%d-\n", k++); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.printf(" %d ", board[i][j]); System.out.printf("\n"); } System.out.printf("\n"); } /* 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 boolean isSafe(int board[][], int row, int col) { 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 boolean solveNQUtil(int board[][], int col) { /* base case: If all queens are placed then return true */ if (col == N) { printSolution(board); return true; } /* Consider this column and try placing this queen in all rows one by one */ boolean 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 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 void solveNQ() { int board[][] = new int[N][N]; if (solveNQUtil(board, 0) == false) { System.out.printf("Solution does not exist"); return ; } return ; } // Driver code public static void main(String[] args) { solveNQ(); } } // This code has been contributed // by 29AjayKumar |
Python3
''' Python3 program to solve N Queen Problem using backtracking '''k = 1 # A utility function to print solution def printSolution(board): global k print(k, "-\n") k = k + 1 for i in range(4): for j in range(4): print(board[i][j], end = " ") print("\n") print("\n") ''' 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 '''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 N Queen problem '''def solveNQUtil(board, col) : ''' base case: If all queens are placed then return true ''' if (col == 4): printSolution(board) 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 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.'''def solveNQ() : board = [[0 for j in range(10)] for i in range(10)] if (solveNQUtil(board, 0) == False): print("Solution does not exist") return return # Driver Code solveNQ() # This code is contributed by YatinGupta |
C#
/* C# program to solve N Queen Problem using backtracking */using System; class GfG { static int N = 4; static int k = 1; /* A utility function to print solution */static void printSolution(int [,]board) { Console.Write("{0}-\n", k++); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(" {0} ", board[i, j]); Console.Write("\n"); } Console.Write("\n"); } /* 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 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) { /* base case: If all queens are placed then return true */ if (col == N) { printSolution(board); 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 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 void solveNQ() { int [,]board = new int[N, N]; if (solveNQUtil(board, 0) == false) { Console.Write("Solution does not exist"); return ; } return ; } // Driver code public static void Main() { solveNQ(); } } /* This code contributed by PrinciRaj1992 */ |
Output:
1- 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 2- 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Printing brackets in Matrix Chain Multiplication Problem
- Printing string in plus â+â pattern in the matrix
- Perfect Sum Problem
- The Celebrity Problem
- 8 queen problem
- N Queen Problem | Backtracking-3
- m Coloring Problem | Backtracking-5
- Gold Mine Problem
- The Knight's tour problem | Backtracking-1
- Word Break Problem using Backtracking
- N Queen Problem using Branch And Bound
- Mobile Numeric Keypad Problem
- Problem of 8 Neighbours of an element in a 2-D Matrix
- Warnsdorff's algorithm for Knightâs tour problem
- Travelling Salesman Problem implementation using BackTracking
- Rat in a Maze Problem when movement in all possible directions is allowed
- Maths behind number of paths in matrix problem
- N-Queen Problem | Local Search using Hill climbing with random neighbour

