zoukankan      html  css  js  c++  java
  • 八皇后问题 回溯法 打印结果

    代码:

    #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 代表的是列。 你也可以反过来想。

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

     

  • 相关阅读:
    BZOJ1087=Codevs2451=洛谷P1896&P2326互不侵犯
    poj1286
    P1066 2^k进制数
    开车旅行
    洛谷P1396 营救
    poj1840
    poj3693
    poj1195
    3955 最长严格上升子序列(加强版)
    1021 玛丽卡
  • 原文地址:https://www.cnblogs.com/stul/p/10665714.html
Copyright © 2011-2022 走看看