八皇后问题 回溯法 打印结果

代码:

#include <iostream>
#include <cmath>
using namespace std;

int n, sum;
const int M = 1e4 + 9;
int x[M];

void print()
{
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (x[i] == j)
                cout << 1 << " ";
            else
                cout << 0 << " ";
        }
        cout << endl;
    }

    cout << endl
         << endl;
}

bool place(int t)
{
    for (int i = 1; i < t; i++)
        if ((abs(x[i] - x[t]) == abs(i - t)) || (x[i] == x[t]))
            return false;
    return true;
}

void backtrack(int t)
{
    if (t > n)
    {
        print();
        sum++;
        return;
    }

    else
        for (int i = 1; i <= n; i++)
        {
            x[t] = i;
            if (place(t))
                backtrack(t + 1);
        }
}

int main()
{
    cin >> n;
    backtrack(1);
    cout << sum << endl;
    return 0;
}

x[i] 的值  代表的是行,i 代表的是列。 你也可以反过来想。

具体看代码,调试的时候可以打印出结果,判断问题所在。

 

原文地址:https://www.cnblogs.com/stul/p/10665714.html