34 N皇后问题Ⅱ

原题网址:https://www.lintcode.com/zh-cn/old/problem/n-queens-ii/

34. N皇后问题 II 

 

讨论区 

根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。

样例

比如n=4,存在2种解决方案

标签 
 
方法同N皇后问题,只不过不生成解决方案而是返回解决方法的个数。
 
1.递归
AC代码:
class Solution {
public:
    /**
     * @param n: The number of queens.
     * @return: The total number of distinct solutions.
     */
    bool canPlaceQ(int row,int col, int * position,int n)
{
    for (int i=0;i<row;i++)
    {
        if (position[i]==col||abs(row-i)==abs(col-position[i]))
        {
            return false;
        }
    }
    return true;
}

void placeQ(int &count,int row,int *position,int n)
{
    if (row==n)
    {
        ++count;
    }
    else
    {
        for (int j=0;j<n;j++)
        {
            if (canPlaceQ(row,j,position,n))
            {
                position[row]=j;
                placeQ(count,row+1,position,n);
            }
        }
    }
}

int totalNQueens(int n)
{
    int count=0;
    if (n<=0)
    {
        return 0;
    }
    int *position=new int[n];
    for (int i=0;i<n;i++)
    {
        position[i]=-1;
    }
    int row=0;
    placeQ(count,row,position,n);

    return count;
}
};

2.非递归

AC代码:

class Solution {
public:
    /**
     * @param n: The number of queens.
     * @return: The total number of distinct solutions.
     */
    bool canPlaceQ(int row,int col, int * position,int n)
{
    for (int i=0;i<row;i++)
    {
        if (position[i]==col||abs(row-i)==abs(col-position[i]))
        {
            return false;
        }
    }
    return true;
}

void placeQ(int &count,int row,int *position,int n)
{
    int i=0,j=0;
    while(i<n)
    {
        while(j<n)
        {
            if (canPlaceQ(i,j,position,n))
            {
                position[i]=j;
                j=0;
                break;
            }
            else
            {
                ++j;
            }
        }

        if (position[i]==-1)
        {
            if (i==0)
            {
                break;
            }
            --i;
            j=position[i]+1;
            position[i]=-1;//注意清空上一行的位置!!;
            continue;
        }

        if (i==n-1)
        {
            ++count;
            j=position[i]+1;//不能用++j,因为寻找到n-1行的列位置后j被重置为0;
            position[i]=-1;
            continue;
        }
        ++i;
    }

}

int totalNQueens(int n)
{
    int count=0;
    if (n<=0)
    {
        return 0;
    }
    int *position=new int[n];
    for (int i=0;i<n;i++)
    {
        position[i]=-1;
    }
    int row=0;
    placeQ(count,row,position,n);

    return count;
}

};

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9061556.html
34