• 用C++实现的八皇后问题


    我是一个C++初学者,控制台实现了一个八皇后问题。

    代码如下:

    //"八皇后问题"V1.0
    //李国良于2017年1月11日编写完成
    
    #include <iostream>
    #include <Windows.h>
    
    using namespace std;
    const int ArSize = 8;//这个数等于几,就是几皇后。
    int num = 0;
    void solve(bool arr[ArSize][ArSize], int row);
    bool check(bool arr[ArSize][ArSize], int row, int column);
    void outPut(bool arr[ArSize][ArSize]);
    
    int main()
    {
    	SetConsoleTitle("八皇后问题");
    	bool chessboard[ArSize][ArSize];
    	for (auto &i : chessboard)
    	{
    		for (auto &j : i)
    		{
    			j = false;
    		}
    	}
    	solve(chessboard, 0);
    	cout << "八皇后问题共有" << num << "种解!" << endl;
    	system("pause");
    	return 0;
    }
    
    void solve(bool arr[ArSize][ArSize], int row)
    {
    	for (int column = 0; column < ArSize; ++column)
    	{
    		arr[row][column] = true;
    		if (check(arr, row, column))
    		{
    			if (row + 1 == ArSize)
    			{
    				outPut(arr);
    			}
    			else
    			{
    				solve(arr, row + 1);
    			}
    		}
    		arr[row][column] = false;
    	}
    }
    
    bool check(bool arr[ArSize][ArSize], int row, int column)
    {
    	if (row == 0)
    	{
    		return true;
    	}
    	int i, j;
    	for (i = 0; i < row; ++i)
    	{
    		if (arr[i][column])
    		{
    			return false;
    		}
    	}
    	i = row - 1;
    	j = column - 1;
    	while (i >= 0 && j >= 0)
    	{
    		if (arr[i][j])
    		{
    			return false;
    		}
    		--i;
    		--j;
    	}
    	i = row - 1;
    	j = column + 1;
    	while (i >= 0 && j <= ArSize - 1)
    	{
    		if (arr[i][j])
    		{
    			return false;
    		}
    		--i;
    		++j;
    	}
    	return true;
    }
    
    void outPut(bool arr[ArSize][ArSize])
    {
    	++num;
    	cout << "**********************" << num << "*********************" << endl;
    	for (int i = 0; i < ArSize; ++i)
    	{
    		for (int j = 0; j < ArSize; ++j)
    		{
    			cout << arr[i][j] << " ";
    		}
    		cout << endl;
    	}
    	cout << "*********************************************" << endl;
    }
    
  • 相关阅读:
    我的2007, 兼谈些对技术的看法
    回帖整理: 关于"学习Java社区"更清晰的思路
    回帖整理: 创业心态
    我的世界观 by 爱因斯坦
    回帖整理: 论团队中的设计工作
    请大家帮我一个忙
    回帖整理: Java社区有什么可学的?
    SSL原理及应用(1)SSL协议体系结构
    文件和目录的访问控制(4) 审核规则
    强名称(2)引用强名称签名的程序集
  • 原文地址:https://www.cnblogs.com/yonggandefeng/p/6275861.html
Copyright © 2020-2023  润新知