PAT (Advanced Level) Practice 1128 N Queens Puzzle (20 分) 凌宸1642
题目描述:
The “eight queens puzzle” is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general N queens problem of placing N non-attacking queens on an N×N chessboard. (From Wikipedia - “Eight queens puzzle”.)
Here you are NOT asked to solve the puzzles. Instead, you are supposed to judge whether or not a given configuration of the chessboard is a solution. To simplify the representation of a chessboard, let us assume that no two queens will be placed in the same column. Then a configuration can be represented by a simple integer sequence (Q1,Q2,⋯,QN), where Qi is the row number of the queen in the i-th column. For example, Figure 1 can be represented by (4, 6, 8, 2, 7, 1, 3, 5) and it is indeed a solution to the 8 queens puzzle; while Figure 2 can be represented by (4, 6, 7, 2, 8, 1, 9, 5, 3) and is NOT a 9 queens’ solution.

译:“八皇后拼图”是将八个象棋皇后放在一个 8×8 的棋盘上,使两个皇后不会相互威胁的问题。 因此,解决方案要求没有两个皇后共享相同的行、列或对角线。 八皇后拼图是将 N 个非攻击皇后放在 N×N 棋盘上的更一般的 N 个皇后问题的一个例子。 (来自维基百科 - “八皇后之谜”。)
在这里,您不需要解决难题。 相反,您应该判断棋盘的给定配置是否是解决方案。 为了简化棋盘的表示,让我们假设不会在同一列中放置两个皇后。 那么一个配置可以用一个简单的整数序列 (Q1 ,Q2 ,⋯,QN ) 来表示,其中 Qi 是第 i 列中皇后的行号。 例如,图 1 可以用 (4, 6, 8, 2, 7, 1, 3, 5) 表示,它确实是 8 皇后拼图的解决方案; 而图 2 可以表示为 (4, 6, 7, 2, 8, 1, 9, 5, 3) 并且不是 9 个皇后的解决方案。
Input Specification (输入说明):
Each input file contains several test cases. The first line gives an integer K (1< K ≤ 200). Then K lines follow, each gives a configuration in the format “N Q1 Q2 … QN”, where 4 ≤ N ≤ 1000 and it is guaranteed that 1≤ Qi ≤N for all i=1,⋯,N. The numbers are separated by spaces.
译:每个输入文件包含几个测试用例。 第一行给出一个整数 K (1<K≤200)。 然后是 K 行,每行给出一个格式为“N Q1 Q2 … QN ”的配置,其中 4 ≤ N ≤ 1000 并且保证 1≤ Qi ≤N 对于所有 i=1,⋯, N。 数字以空格分隔。
output Specification (输出说明):
For each configuration, if it is a solution to the N queens problem, print YES in a line; or NO if not.
译:对于每个配置,如果是N皇后问题的解决方案,则在一行打印YES; 否则打印 NO 。
Sample Input (样例输入):
4
8 4 6 8 2 7 1 3 5
9 4 6 7 2 8 1 9 5 3
6 1 5 2 6 4 3
5 1 3 5 2 4
Sample Output (样例输出):
YES
NO
NO
YES
The Idea:
- 考察的是什么时候满足 N-皇后 问题的解的情况,这里题目中已经保证了不会出现在同一列,那么只要不再出现在同一行,已经不出现在对角线上,即使满足要求的解
The Codes:
#include<bits/stdc++.h>
using namespace std ;
int n , num[1010] , k;
bool deal(int n){
for(int i = 0 ; i < n - 2 ; i ++){
for(int j = i + 1 ; j < n ; j ++){
if((abs(num[i] - num[j]) == abs(i - j)) || num[i] == num[j]) return false ;
}
}
return true ;
}
int main(){
cin >> k ;
while(k --){
cin >> n ;
for(int i = 0 ; i < n ; i ++) cin >> num[i] ;
if(deal(n)) cout << "YES" << endl ;
else cout << "NO" << endl ;
}
return 0 ;
}
该博客主要讨论如何判断一个给定的棋盘配置是否符合N皇后问题的解。N皇后问题要求在N×N的棋盘上放置N个皇后,使得没有两个皇后在同一行、列或对角线上。博客提供了输入输出规格,并展示了一个C++代码示例,用于检查给定配置是否符合条件。
686

被折叠的 条评论
为什么被折叠?



