首页 > 其他 > 详细

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

时间:2019-04-07 16:39:45      阅读:99      评论:0      收藏:0      [点我收藏+]

代码:

#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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!