// Returns true if a queen can be placed
// in kth row and ith column. Otherwise it
// returns false. X is a global array
// whose first (k-1) values have been set.
// Abs( ) returns absolute value of r
for j := 1 to k-1 do
// Two in the same column
// or in the same diagonal
if ((x[j] == i) or
(abs(x[j] – i) = Abs(j – k)))
then return false;
Algorithm nQueens(k, n) :
// Using backtracking, this procedure prints all
// possible placements of n queens on an n×n
// chessboard so that they are nonattacking.
for i:= 1 to n do
if Place(k, i) then
x[k] = i;
if (k == n)
The time and space complexity of the given code for the N-Queens problem can be analyzed as follows:
Time Complexity: The algorithm uses backtracking to generate all possible solutions for placing N queens on an N x N chessboard. The backtracking algorithm recursively explores all possible solutions by checking whether a queen can be placed in each column of the current row. The time complexity of the algorithm can be expressed as O(N!) because in the worst case scenario, every queen must be tried in every column of every row.
Space Complexity: The space complexity of the algorithm depends on the size of the input problem, which is N. In the given code, an array ‘arr’ of size N is used to store the column index of the queen in each row. Additionally, a variable ‘no’ is used to count the number of valid solutions found. Therefore, the space complexity of the algorithm can be expressed as O(N).
In summary, the time complexity of the algorithm is O(N!), and the space complexity is O(N).
Please Login to comment...