Algorithm of N queens

前端 未结 5 714
有刺的猬
有刺的猬 2021-01-13 04:47
Algorithm NQueens ( k, n) //Prints all Solution to the n-queens problem
{
    for i := 1 to n do
    {
        if Place (k, i) then
        {
            x[k] := i;
         


        
5条回答
  •  暖寄归人
    2021-01-13 05:06

    I have code for this without using backtracking, but the nice thing is, it is giving time complexity of big-oh(n).

    // when n is even...
    for(j=1;j<=n/2;j++)
    {
        x[j]=2*j;
    };
    i=1;
    for(j=n/2 +1 ;j<=n;j++)
    {
        x[j] =i;
        i=(2*i)+1;
    }
    
    // when n is odd..
    i=0;
    for(j=1;j<=(n/2+1);j++)
    {
        x[i] = (2*i)+1;
        i++;
    }
    i=1;
    for(j=(n/2+2);j<=n;j++)
    {
        x[j] = 2*i;
        i++;
    }
    

    This code works well and gives one solution, but now I am in search of getting all possible solutions using this algorithm.

提交回复
热议问题