![]() |
VOOZH | about |
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 NQueen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.
👁 N-Queen-ProblemFor example, the following is a solution for the 4 Queen problem.
👁 Solution-Of-4-Queen-ProblemExamples:
Input: n = 4
Output: [2, 4, 1, 3]
Explanation: [2, 4, 1, 3 ] and [3, 1, 4, 2] are the two possible solutions.Input: n = 1
Output: [1]
Explanation: Only one queen can be placed in the single cell available.
Algorithm :
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 array arr[] of size n to mark the cells occupied 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, check if any other queen is placed either in same column or same diagonal (row is not possible, as we are increasing it by 1):
- if arr[j] == i: it means that other queen is already placed in this column.
- if abs(arr[j] - i) == abs(j - k)): it means that other queen is already placed in this diagonal.
Implementation:
2 4 1 3
Time Complexity: O(n!), because in the worst case scenario, every queen must be tried in every column of every row.
Space Complexity: O(n), an array of maximum possible size of n is used to store the column index.