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

    EightOfQueen.h

    #ifndef EIGHTOFQUEEN_H_INCLUDED
    #define EIGHTOFQUEEN_H_INCLUDED
    
    #include <string>
    using namespace std;
    
    class QueenChess
    {
    public:
        QueenChess();
        void Solve();
        string chess[8];
        int solves;
    private:
        bool SafeJudge(int row,int col) const;
        void PlaceQueen(int row);
        void DrawChess() const;
    };
    
    
    #endif // EIGHTOFQUEEN_H_INCLUDED

    EightOfQueen.cpp

    #include <iostream>
    #include "EightOfQueen.h"
    #include <cstring>
    
    using namespace std;
    
    void start()
    {
        QueenChess Qchess;
        Qchess.Solve();
    }
    
    //判断是否安全
    bool QueenChess::SafeJudge(int row,int col) const
    {
        int qrow,qcol;
        //只检查与前面的棋子是否安全
        for(qrow=0;qrow<row;qrow++)
        {
            string row_string = chess[qrow];
            qcol = row_string.find("Q");
            if(qrow == row || qcol == col || (qcol-qrow) == (col-row) || (qcol+qrow) == (row + col))
            {
                return false;
            }
        }
        return true;
    }
    
    //打印
    void QueenChess::DrawChess() const
    {
        cout << "\n第" << solves << "个解为:"<< endl;
        cout << "   1 2 3 4 5 6 7" << endl;
        for(int i=0;i<8;i++)
        {
            cout << i << " ";
            for(int j=0;j<8;j++)
            {
                cout << chess[i][j] << " ";
            }
            cout << endl;
        }
    }
    
    //放置各列的棋子
    void QueenChess::PlaceQueen(int row)
    {
        for(int col=0;col<8;col++)
        {
            if(SafeJudge(row,col))      //是否安全才能放置
            {
                chess[row][col] = 'Q';
                if(row < 7)
                {
                    PlaceQueen(row+1);
                }
                else
                {
                    solves++;
                    DrawChess();
                }
            }
            //chess[row] = "--------";
        }
    }
    
    //给出纺织成功的棋盘总数
    void QueenChess::Solve()
    {
        PlaceQueen(0);          //第0行开始放置
        cout << "总共解的个数:" << solves << endl;
    }
    
    //构造函数,初始化棋盘
    QueenChess::QueenChess()
    {
        solves = 0;
        for(int i=0;i<8;i++)
        {
            chess[i] = "--------";
        }
    }
    
    int main()
    {
        start();
        return 0;
    }
  • 相关阅读:
    若依项目上传下载附件实现
    若依项目实现导入功能
    若依项目开发实践
    若依项目人员选择器实现
    springboot打成Jar包后部署至Linux服务器上
    linux下启动tomcat----Cannot find ./catalina.sh
    Linux下更换jdk和配置环境变量
    若依项目分模块集成uflo2
    若依项目模块化开发
    Java中涉及到金额业务的处理
  • 原文地址:https://www.cnblogs.com/wn19910213/p/3463117.html
Copyright © 2011-2022 走看看