I have this questions which may be basic to ask, but I am finding it hard to understand. How to determine time complexity of nQueens. In some post it says its n, because in (4*4) matrix. each queen gets one row & as the queens moved down the rows the column option reduces (n * n-1 * n-2..,) which is fine. but in recursive algorithm we pass rowIndex and for each call we check if queen can be placed in a cell looping thru all columns & then call solveNQueens for rowIndex+1. In this case is time complexity still n!
bool solveNQueens(rowIndex, matrix)
{
//recursion base case to exit
//decision tree
for (int i = 0; i<4; i++)
{
if(cellAvailable)
{
solveNQueens(rowIndex+1, matrix);
}
}
}
In fact O(n!)
is an upper bound. But as this article explains , the number of solutions is roughly (0.143n)^n
. So that gives a super-exponential lower bound.
Coming up with a better answer is likely to be an open research problem. But I expect that the lower bound is in the right ballpark for what the algorithm takes to produce all answers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.