zoukankan      html  css  js  c++  java
  • 递归---n皇后

    ---恢复内容开始---

    #include "stdafx.h"
    #include <iostream>
    #include <fstream> //文件流
    #include <iomanip>
    #include <cstdlib>
    
    using namespace std;
    void queenSolve(int rowCurrent, int n, int *&queenlist, int &count, ofstream &os);
    void Print(int n, int *&queenlist, ofstream &os);
    bool Check(int rowCurrent, int *&queelist);
    
    int main()
    {
        int n;
        cout << "请输入规模n:  " << endl;
        cin >> n;
        if (n<4)
        {
            cerr << "问题规模必须大于4" << endl;
            return 0;
        }
    
        int *queenlist = new int[n];
        int count = 0;
        ofstream os;
        os.open("result.txt");
        queenSolve(0,n, queenlist, count, os);
        cout << "共有" << count << "种解法" << endl;
        os.close();
    
        system("pause");
        return 0;
    }
    void Print(int n, int *&queenlist, ofstream &os){
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++){
                os <<(queenlist[i] == j ? 1 : 0);
                os << setw(2); //设置域宽为n个字符,<iomanip>
            }
            os << "
    ";
        }
        os << "
    ";
    }
    bool Check(int rowCurrent, int *&queelist){
        for (int i = 0; i < rowCurrent; i++){
            if (queelist[rowCurrent] == queelist[i])
                return false;
            if (abs(rowCurrent - i) == abs(queelist[rowCurrent] - queelist[i]))   //<cstdlib>
                return false;
        }
        return true;
    }
    void queenSolve(int rowCurrent, int n, int *&queenlist, int &count, ofstream &os)
    {
        if (rowCurrent == n)
        {
            ++count;
            os << "" << count << "个解" << endl;
            Print(n,queenlist,os);
        }
        else{
            for (int i = 0; i < n; i++)
            {
                queenlist[rowCurrent] = i;
                if (Check(rowCurrent, queenlist))
                    queenSolve(rowCurrent+1, n, queenlist, count, os);
            }        
        }
    }

    ---恢复内容结束---

  • 相关阅读:
    linux网络connect: network is unreachable的解决记录
    kali系统输入msfvenom -l为什么不能显示
    基于fluxion 6.9 钓鱼wifi
    【操作系统】Linux
    【JAVA基础】Mybatis 基本应用
    饮冰三年-人工智能-Vue-70 Promise
    饮冰三年-人工智能-Vue-69 路由
    饮冰三年-人工智能-Vue-68 CLI
    饮冰三年-人工智能-Vue-67 Webpack
    饮冰三年-人工智能-Vue-66 Vue组件化
  • 原文地址:https://www.cnblogs.com/wxquare/p/4491407.html
Copyright © 2011-2022 走看看