Solving the N-Queen Problem Using Backtracking in Java
By Rohit Sharma
Updated on Apr 01, 2025 | 9 min read | 1.72K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Apr 01, 2025 | 9 min read | 1.72K+ views
Share:
Table of Contents
Let’s imagine you’re staring at a chessboard. It’s a standard N×N grid, and you need to place N queens on this board. But here’s the catch: No two queens can threaten each other. As you know, queens can move vertically, horizontally, and diagonally across the board. So, how do we place them on the board without them coming into conflict?
This is exactly what the N-Queen problem is all about. It's a classic example of a problem where we can apply backtracking, an algorithmic technique that tries all possible configurations but abandons those that don’t lead to a solution.
In this blog, we’ll dive deep into solving the N-Queen problem using backtracking in Java. I’ll explain how it works, why backtracking is a perfect fit for this, and walk you through a full Java code example that will help you visualize the process.
Get data science certification from the World’s top Universities. Learn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Popular Data Science Programs
Before we jump into the code, let's make sure we fully understand the N-Queen problem. The N-Queen problem is all about placing N queens on an N×N chessboard. The twist is that no two queens can attack each other. This means that:
For example:
Must Explore: What are Data Structures & Algorithm
When you think about it, backtracking is an incredibly effective approach to solving the N-Queen problem. Here's why:
In the N-Queen problem, this means:
This way, backtracking ensures that we explore all possible configurations but avoid checking invalid ones, saving a ton of time and effort.
Also Explore: Top 14 Most Common Data Mining Algorithms You Should Know
Data Science Courses to upskill
Explore Data Science Courses for Career Progression
The approach to solving the N-Queen problem can be broken down into three main steps:
The Key Constraints to Check:
Time Complexity:
Also Read: Top 10 Data Structures & Algorithm Interview Questions & Answers
Now, let’s look at the Java code for solving the N-Queen problem using backtracking. Here’s how you can implement it:
Java Code:
public class NQueen {
// Function to solve the N-Queen problem using backtracking
public static boolean solveNQueens(int n) {
// Create a 2D board of size n x n
int[][] board = new int[n][n];
// Arrays to keep track of columns and diagonals under attack
boolean[] cols = new boolean[n]; // Columns
boolean[] diag1 = new boolean[2 * n - 1]; // Diagonals with positive slope
boolean[] diag2 = new boolean[2 * n - 1]; // Diagonals with negative slope
// Start the backtracking process to solve the N-Queen problem
if (placeQueens(board, 0, n, cols, diag1, diag2)) {
printSolution(board);
return true;
} else {
System.out.println("Solution does not exist.");
return false;
}
}
// Function to place queens using backtracking
private static boolean placeQueens(int[][] board, int row, int n, boolean[] cols, boolean[] diag1, boolean[] diag2) {
// If all queens are placed, return true
if (row == n) {
return true;
}
// Try placing a queen in each column for the current row
for (int col = 0; col < n; col++) {
// Check if the queen can be placed at (row, col)
if (cols[col] || diag1[row - col + n - 1] || diag2[row + col]) {
continue; // Skip if the position is under attack
}
// Place the queen
board[row][col] = 1;
cols[col] = true;
diag1[row - col + n - 1] = true;
diag2[row + col] = true;
// Recur to place queens in the next row
if (placeQueens(board, row + 1, n, cols, diag1, diag2)) {
return true; // If a valid configuration is found, return true
}
// Backtrack if placing queen at (row, col) doesn't lead to a solution
board[row][col] = 0;
cols[col] = false;
diag1[row - col + n - 1] = false;
diag2[row + col] = false;
}
// If no position is found for the queen in this row, return false
return false;
}
// Function to print the solution
private static void printSolution(int[][] board) {
System.out.println("Solution:");
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] == 1 ? "Q " : ". ");
}
System.out.println();
}
}
public static void main(String[] args) {
int n = 8; // Change the size of the board here
solveNQueens(n);
}
}
Explanation of the Code:
Example Output
Let’s say we run this code with n = 8 (the classic 8-Queen problem). The output might look something like this:
Solution:
. . . . Q . . .
Q . . . . . . .
. . . . . . Q .
. . . Q . . . .
. . . . . Q . .
. . Q . . . . .
. Q . . . . . .
. . . . . . . Q
The N-Queen problem is a fantastic example of how backtracking can be used to solve complex problems efficiently. By trying different configurations, pruning invalid options, and backtracking when necessary, backtracking algorithms can explore huge solution spaces in a smart way.
In this blog, I walked you through the entire process of solving the N-Queen problem using Java and backtracking. Hopefully, this gave you a solid understanding of both the problem and the algorithm, along with the logic behind how the backtracking technique works.
The N-Queen problem is a classic puzzle, and solving it can be both fun and insightful. It’s also a great way to deepen your understanding of recursive algorithms, backtracking, and optimization techniques in computer science.
If you have any questions or want to explore more variations of the problem, feel free to ask!
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
The N-Queen problem involves placing N queens on an N×N chessboard such that no two queens threaten each other. This means no two queens can be in the same row, column, or diagonal.
Backtracking is used to explore all possible placements of queens on the board, recursively placing queens row by row. If a conflict is found, the algorithm backtracks and tries a different configuration.
Backtracking is ideal for the N-Queen problem because it allows efficient pruning of the solution space. If a queen placement is invalid, the algorithm immediately stops exploring that path and backtracks to try a different one.
The time complexity of backtracking for the N-Queen problem is O(N!), since we attempt to place queens in every column of each row. However, backtracking reduces unnecessary configurations, making it faster than brute force.
The algorithm checks for validity by ensuring no queens share the same column or diagonal. This is done using three arrays: one for columns and two for diagonals (positive and negative slopes).
The Java code uses a 2D array to represent the chessboard, and boolean arrays to track column and diagonal conflicts. It recursively places queens row by row, backtracking if a valid configuration isn’t found.
Yes, the N-Queen problem can be solved for any N. However, the number of possible solutions increases factorially, so for large N (e.g., N=100), the problem becomes computationally intensive.
The output is a chessboard where each queen (represented by "Q") is placed such that no two queens threaten each other. The output is a visual representation of one of the possible valid configurations.
The main constraints are that no two queens can share the same row, column, or diagonal. The algorithm must respect these constraints when placing each queen.
The Java code prints the board with "Q" for queens and "." for empty spaces, visually showing one valid solution where no queens threaten each other.
The N-Queen problem is a great exercise for learning backtracking because it involves exploring multiple configurations, pruning invalid paths, and applying recursive techniques, making it a practical way to understand problem-solving with backtracking.
834 articles published
Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources