logo Algorithm Visualizer theory Visualizer Quiz Forum

n-Queen Problem

The n queen problem is solved using a backtracking algorithm, where the board is recursively filled with queens, one at a time, and backtracked if no valid solution is found. At each step, the algorithm checks if the newly placed queen conflicts with any previously placed queens, and backtracks if a conflict is found. The process continues until all N queens are placed on the board without conflicts, or all possible solutions have been explored. The resulting board represents a valid solution to the N queen problem.



What is Backtracking?

Backtracking is a problem-solving technique that involves recursively trying out different solutions to a problem, and backtracking or undoing previous choices when they dont lead to a valid solution. It is commonly used in algorithms that search for all possible solutions to a problem, such as the famous eight-queens puzzle. Backtracking is a powerful and versatile technique that can be used to solve a wide range of problems.

Backtracking is often used in constraint satisfaction problems, such as the N Queen problem, where we need to find a solution that satisfies a set of constraints. In these problems, we start by choosing a value for one of the variables and checking if it satisfies the constraints. If it does, we move on to the next variable and repeat the process. If the current value does not satisfy the constraints, we backtrack to the previous variable and try a different value.

Backtracking is an effective technique for solving problems, as it allows us to incrementally build a solution and avoids the need to consider all possible solutions from scratch. However, it can also be time-consuming, as it requires many iterations and checks. To make backtracking more efficient, various optimization techniques, such as constraint propagation and heuristics, can be used.

Problem Statement

How can n queens be placed on an nxn chessboard so that no two of them attack each other.

Solution to the n-Queens Problem

The way we try to solve this is by placing a queen at a position and trying to rule out the possibility of it being under attack. We place one queen in each row/column. If we see that the queen is under attack at its chosen position, we try the next position. If a queen is under attack at all the positions in a row, we backtrack and change the position of the queen placed prior to the current position. We repeat this process of placing a queen and backtracking until all the N queens are placed successfully.

Algorithms

Following is the algorithm for the n-Queens problem:

  • Start in the leftmost column

  • If all queens are placed, return true

  • Try all rows in the current column. For each row:

  • If the queen can be placed safely in this row, mark this cell and recursively try placing the rest of the queen

  • b. If placing the queen in this row leads to an unsafe configuration, unmark the cell and try the next row

  • If all rows have been tried and nothing worked, return false to trigger backtracking

Approaches to Solve n Queen Problem

Below we have discussed approaches to solve the N Queen Problem

Approach 1: Naive Approach to Solve N Queen Problem

The naive approach is to generate all possible configurations of queens on board and print a configuration that satisfies the given constraints. We generate all possible configurations and one by one check if a configuration satisfies the given constraints or not. For every checked configuration, we check if queens in this configuration can attack each other or not. If we find a configuration satisfying the given constraints, we print it.

                        
                            while there are unexplored configurations.
                                {
                                generate the next configuration
                                if queens don't attack in this configuration then
                                    {
                                        print this configuration;
                                    }
                                }
                        

Approach 2: Backtracking Algorithm to Solve N Queen Problem

By using backtracking we position queens in different columns one by one, beginning with the leftmost column. When we position a queen in a column, we look for clashes with other queens that have already been placed. If we locate a row in the current column with no collision, we mark this row and column as part of the solution. We backtrack and return false if we cannot discover such a row due to clashes.

                                function solveNQueens(board, col, n):
                                    if col >= n:
                                        print board
                                        return true
                                    for row from 0 to n-1:
                                        if isSafe(board, row, col, n):
                                        board[row][col] = 1
                                        if solveNQueens(board, col+1, n):
                                            return true
                                        board[row][col] = 0
                                    return false

                                    function isSafe(board, row, col, n):
                                    for i from 0 to col-1:
                                        if board[row][i] == 1:
                                        return false
                                    for i,j from row-1, col-1 to 0, 0 by -1:
                                        if board[i][j] == 1:
                                        return false
                                    for i,j from row+1, col-1 to n-1, 0 by 1, -1:
                                        if board[i][j] == 1:
                                        return false
                                    return true

                                    board = empty NxN chessboard
                                    solveNQueens(board, 0, N)
                            

Approach 3: Backtracking with optimization

The reason behind the N queen problem approach is that instead of checking every element in the right and left diagonals, we can use the property of diagonals:

  1. For each right diagonal, the sum of I and j is constant and unique, where i represents row and j represents a column in the chess board.

  2. The difference between i and j is constant and unique for each left diagonal, where i and j represent the row and column of the chess board, respectively.

Complexity Analysis

Time Complexity: Since in each row we are iterating for N times and it costs O(1) time to check if placing the queen in a cell is valid. Therefore, the recurrence relation of the above algorithm is T(n)= n×T(n-1) which evaluates to O(N!)
Space Complexity: Since, we are using a 2-dimensional array of dimension n×n, therefore the overall time complexity is O(N^2). However, we can say that constant extra space is required to find the answer (if we do not account space needed to store the answer).

Conclusion

In conclusion, the N queen problem is a challenging problem that can be solved using a backtracking algorithm. The problem requires careful consideration of the rules governing the placement of queens on a chessboard, and the backtracking algorithm provides an efficient way to search for all possible solutions. The N queen problem has practical applications in areas such as computer vision, where it can be used to solve problems such as object recognition and tracking. So, understanding how to solve the N queen problem using backtracking is an important skill for any programmer.

Frequently Asked Questions

Below we have discussed some frequently asked questions regarding N Queen Problem

  1. What is the goal of the N Queen problem?
    Ans: The goal of the N Queen problem is to find a configuration of the N queens on an NxN chessboard such that no two queens are attacking each other

  2. What is a valid solution to the N Queen problem?
    Ans: A valid solution to the N Queen problem is a configuration of the N queens on an NxN chessboard such that no two queens are in the same row, column, or diagonal.

  3. What is the brute force approach to solving the N Queen problem?
    Ans: The brute force approach to solving the N Queen problem involves trying all possible combinations of placing the N queens on the chessboard and checking if each combination satisfies the constraints (i.e., no two queens are in the same row, column, or diagonal).

  4. What is the backtracking approach to solving the N Queen problem?
    Ans: The backtracking approach to solving the N Queen problem is a more efficient solution compared to the brute force approach. In this approach, we start by placing the first queen in the first row, then move to the next row and try to place the next queen, and so on. If we reach a point where it is not possible to place a queen, we backtrack and try a different position for the previous queen. We continue this process until we find a valid solution or all possibilities have been exhausted.

  5. How can I solve the n-Queen problem?
    Ans: There are several algorithms to solve the n-Queen problem, such as backtracking, genetic algorithms, and simulated annealing. The most common algorithm is backtracking, which involves trying to place queens on the board row by row, backtracking when a conflict is found, and continuing until a solution is found.

  6. Can the n-Queen problem be solved for all values of n?
    Ans: The n-Queen problem can be solved for all values of n, but the computational complexity of finding a solution increases rapidly as n increases. For large values of n, it may not be practical to find a solution using a brute-force algorithm.

1 2 3 4 5 »