USACO1.5 八皇后 Checker Challenge

八皇后-洛谷

题目描述

一个如下的 6 × 6 6 \times 6 6×6 的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行、每列有且只有一个,每条对角线(包括两条主对角线的所有平行线)上至多有一个棋子。

上面的布局可以用序列 2   4   6   1   3   5 2\ 4\ 6\ 1\ 3\ 5 2 4 6 1 3 5 来描述,第 i i i 个数字表示在第 i i i 行的相应位置有一个棋子,如下:

行号 1   2   3   4   5   6 1\ 2\ 3\ 4\ 5\ 6 1 2 3 4 5 6

列号 2   4   6   1   3   5 2\ 4\ 6\ 1\ 3\ 5 2 4 6 1 3 5

这只是棋子放置的一个解。请编一个程序找出所有棋子放置的解。
并把它们以上面的序列方法输出,解按字典顺序排列。
请输出前 3 3 3 个解。最后一行是解的总个数。

输入格式

一行一个正整数 n n n,表示棋盘是 n × n n \times n n×n 大小的。

6
输出格式

前三行为前三个解,每个解的两个数字之间用一个空格隔开。第四行只有一个数字,表示解的总数。

2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4
提示

【数据范围】
对于 100 % 100\% 100% 的数据, 6 ≤ n ≤ 13 6 \le n \le 13 6n13

题目翻译来自NOCOW。
USACO Training Section 1.5

题目标签
  • 搜索 DFS 标记 回溯
解题思路
  1. 每列、每行、每斜行(\,/)都只能出现一个棋子。
    分别用数组表示棋子出现状态,bool类型即可。
  2. 输出任意3个符合条件的棋子数据。
    输出前三组,后续只进行计数。
  3. 输出符合条件摆放方式的个数。
AC代码
/**
 * @problem: P1219 [USACO1.5] 八皇后 Checker Challenge
 * @link: https://www.luogu.com.cn/problem/P1219
 * @category: DFS 
 * @date: Mon Jul 17 08:54:13 CST 2023
 * @author: YaeSaraki
 **/

// #pragma GCC optimize("O2")

#include <algorithm>
#include <iostream>
#include <set>

#define DBG(x) cout << #x << " = " << (x) << '\n'

using namespace std;

int n;
vector<bool> r, rc, cr;
vector<int> board;
set<double> slopeSet;
int times = 0; // int times: Record the number of conditions conformed.

void Print() {
  if (times <= 3) for (int i = 0; i < board.size(); ++i)
      cout << board.at(i) << " \n"[i == board.size() - 1];
}

void DFS(int u) { // int u: represent the corrent row.
  if (u == n) { ++times; Print(); return; }
  for (int i = 0;  i < n; ++i) {
    int t1 = i - u + n, t2 = i + u; // int t1, t2: Respectively represent oblique line(/ & \).

    if (!r.at(i) && !rc.at(t1) && !cr.at(t2)) { // Judge whether the condition conformed.
      /** tag the corrent column, ablique line. */
      r.at(i) = rc.at(t1) = cr.at(t2) = true;
      board.push_back(i + 1);

      /** Search the next row. */
      DFS(u + 1);

      /** Remove the tag, backtrack. */
      r.at(i) = rc.at(t1) = cr.at(t2) = false;
      board.pop_back();

    }
  }
} 

inline void solve() {
  cin >> n;
  rc = cr = vector<bool> (2 * n);
  r = vector<bool> (n);
  DFS(0);
  cout << times << '\n';
}

bool rt = false;
signed main() {
  ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
  freopen("test.in", "r", stdin);
#endif
  if (rt) { int T; cin >> T; while (T--) solve(); }
  else solve();
  return (0 ^ 0);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值