www.luogu.com.cn
基本思路
深度优先搜索(DFS)
由于题目数据很小(6≤n≤13),我们可以采用打表深度优先搜索的方式完成这道题。
定义四个布尔数组分别表示表格的行,列,两个对角线上是否有旗子存在。
如图所示。

抽象代码如下↓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
   | #include <bits/stdc++.h> using namespace std;
  const int N = 50; int n, sum, a[N], b[N], c[N], d[N];
 
 
  void dfs(int i)  {     if (i > n)      {         if (sum <= 2)          {             for (int k = 1; k <= n; k++)                 cout << a[k] << ' ';             cout << endl;         }         sum++;	         return;      }
      for (int j = 1; j <= n; j++)      {         if ((!b[j]) && (!c[j + i]) && (!d[i - j + n]))         {             a[i] = j;             b[j] = 1;             c[i + j] = 1;             d[i - j + n] = 1; 
              dfs(i + 1); 
              b[j] = 0;             c[i + j] = 0;             d[i - j + n] = 0;                       }     } }
  int main() {     cin >> n; 
      dfs(1); 
      cout << sum << endl;     return 0; }
   |