zoukankan      html  css  js  c++  java
  • N皇后问题

    TestNQueen.cpp

     

    #include <iostream>

    #include "Queen.h"

    using namespace std;

     

    int main()

    {

        cout << "输入皇后个数";

        int n;

        cin >> n;

        int* M = new int[n];

        int* L = new int[2 * n];

        int* R = new int[2 * n];

        int** A = new int*[n];

        for(int i = 0; i < n; ++i)

        {

            A[i] = new int[n];

            for(int j = 0; j < n; ++j)

            {

                A[i][j] = 0;

            }

     

            M[i] = 0;

        }

        for(int i = 0; i < 2 * n; ++i)

        {

            L[i] = 0;

            R[i] = 0;

        }

     

        int p = mytry(0, M, L, R, A, n);

        cout << "共有" << p << "种方案" << endl;

        system("pause");

        return 0;

    }

     

    Queen.h

     

    #include <iostream>

    using namespace std;

     

    int qCount = 0;

     

    void print(int** A, int n)

    {

        for(int i = 0; i < n; ++i)

        {

            for(int j = 0; j < n; ++j)

            {

                cout << A[i][j] << "  ";

            }

            cout << endl;

        }

        cout << "------------------------------" << endl;

    }

     

    int mytry(int i, int* M, int* L, int* R, int** A, int n)

    {

        for(int j = 0; j < n; ++j)

        {

            if (!M[j] && !L[i + j] && !R[i - j + n])

            {

                A[i][j] = i + 1;

                M[j] = L[i + j] = R[i - j + n] = 1;

     

                if (i == n - 1)

                {

                    print(A, n);

                    ++qCount;

                }

     

                else

                {

                    mytry(i + 1, M, L, R, A, n);

                }

     

                 A[i][j] = 0;

                 M[j] = L[i + j] = R[i - j + n] = 0;

             }

        }

        return qCount;

    }

  • 相关阅读:
    @Aspect 注解使用详解
    Mysql的4个隔离级别
    【学习笔记】二分类问题中的“最大似然”与“交叉熵损失”概念的理解
    【转】对“先验概率”与“后验概率”概念的通俗理解
    nginx——安装部署vue项目
    JWT
    Vue——自定义组件实现vmodel
    Vue——子级向父级传递参数
    SpringBoot2(十四)全局异常切面
    Vue——ElementUI表格分页
  • 原文地址:https://www.cnblogs.com/720139h/p/3474617.html
Copyright © 2011-2022 走看看