八皇后
  • 板块灌水区
  • 楼主LoneWolf
  • 当前回复3
  • 已保存回复3
  • 发布时间2021/11/20 18:57
  • 上次更新2023/11/3 23:57:27
查看原帖
八皇后
338833
LoneWolf楼主2021/11/20 18:57

rt,

#include <iostream>
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()
{
    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;
}

11行报错,

报错信息:[Error] range-based 'for' loops are not allowed in C++98 mode

2021/11/20 18:57
加载中...