• N-Queens II


    Description:

    Follow up for N-Queens problem.

    Now, instead outputting board configurations, return the total number of distinct solutions.

    Code:

    #define NUM 100
    int x[NUM];
    class Solution {
    public:
        bool isValid(int k)
        {
            for (int i = 1; i < k; ++i)
            {
                if (x[i] == x[k] || abs(k-i)==abs(x[k]-x[i]) )
                    return false;
            }
            return true;
        }
        int totalNQueens(int n) {
            
           for (int i = 0; i < NUM; ++i)
            x[i] = 0;
            
            int k = 1,number = 0;
            while ( k >= 1 )
            {
                x[k]+=1;
                while (x[k] <= n && !isValid(k))
                    x[k]+=1;
                if ( x[k] <= n && k == n)
                {
                    number++;
                }
                else if ( x[k] <= n && k < n)
                {
                    k = k+1;
                }
                else
                {
                    x[k] = 0;
                    k = k-1;
                }
            }
            return number;
        }
    };
  • 相关阅读:
    链表详解自带代码
    队列
    单词翻转
    表达式求值
    一元多项式
    循环链表
    学生成绩管理系统
    双向循环链表
    双向链表
    静态链表
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4784413.html
Copyright © 2020-2023  润新知