AcWing 1621. N 皇后问题
原题链接
简单
作者:
王小强
,
2021-03-19 22:34:30
,
所有人可见
,
阅读 445
纯凭感觉写的题,居然过了
#include <iostream>
#include <vector>
using namespace std;
int k;
bool check(vector<vector<int>>& grid, int n) {
for (int y = 1; y <= n; ++y) {
int cnt = 0;
for (int x = 1; x <= n; ++x) cnt += grid[y][x];
if (cnt != 1) return false;
}
for (int y = 1; y <= n; ++y) {
for (int x = 1; x <= n; ++x) {
int cx, cy;
if (grid[y][x]) {
cx = x + 1, cy = y + 1; // 向右下角走
while (cx >= 1 && cx <= n && cy >= 1 && cy <= n) {
if (grid[cy][cx]) return false;
cx += 1, cy += 1;
}
cx = x - 1, cy = y - 1; // 向左上角走
while (cx >= 1 && cx <= n && cy >= 1 && cy <= n) {
if (grid[cy][cx]) return false;
cx -= 1, cy -= 1;
}
cx = x + 1, cy = y - 1; // 向右上角走
while (cx >= 1 && cx <= n && cy >= 1 && cy <= n) {
if (grid[cy][cx]) return false;
cx += 1, cy -= 1;
}
cx = x - 1, cy = y + 1; // 向左下角走
while (cx >= 1 && cx <= n && cy >= 1 && cy <= n) {
if (grid[cy][cx]) return false;
cx -= 1, cy += 1;
}
}
}
}
return true;
}
int main(void) {
cin >> k;
while (k--) {
int n;
cin >> n;
vector<vector<int>> grid(n + 1, vector<int>(n + 1, 0));
for (int x = 1; x <= n; ++x) {
int y;
cin >> y;
grid[n - y + 1][x] = 1;
}
puts(check(grid, n) ? "YES" : "NO");
}
return 0;
}