1128 N Queens Puzzle
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1128 N Queens Puzzle相关的知识,希望对你有一定的参考价值。
The "eight queens puzzle" is the problem of placing eight chess queens on an 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 (, where Q?i?? 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.
Figure 1 | Figure 2 |
Input Specification:
Each input file contains several test cases. The first line gives an integer K (1). Then K lines follow, each gives a configuration in the format "N Q?1?? Q?2?? ... Q?N??", where 4 and it is guaranteed that 1 for all ,. The numbers are separated by spaces.
Output Specification:
For each configuration, if it is a solution to the N queens problem, print YES
in a line; or NO
if not.
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
题意:
给出N个皇后所在的位置判断是不是满足N皇后的要求。
思路:
本来想着建立一个棋盘,把N个皇后放在相应的位置上,然后上下左右遍历判断。后来发现这样不仅麻烦而且很low,然后就想到了根据位置的关系abs(v[j] - v[p]) == abs(j - p)来判断是不是在对角线上。
Code:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int main() { 6 int n, k, t; 7 bool isSolution; 8 cin >> n; 9 for (int i = 0; i < n; ++i) { 10 cin >> k; 11 vector<int> v(k + 5); 12 set<int> s; 13 isSolution = true; 14 for (int j = 1; j <= k; ++j) cin >> v[j]; 15 for (int j = 1; j <= k; ++j) { 16 for (int p = j + 1; p < k; ++p) { 17 if ( v[j] == v[p] || abs(v[j] - v[p]) == abs(j - p)) { 18 isSolution = false; 19 break; 20 } 21 } 22 if (!isSolution) break; 23 } 24 if (isSolution) 25 cout << "YES" << endl; 26 else 27 cout << "NO" << endl; 28 } 29 return 0; 30 }
以上是关于1128 N Queens Puzzle的主要内容,如果未能解决你的问题,请参考以下文章
PAT A1128 N Queens Puzzle (20 分)
1128 N Queens Puzzle (20 分)难度: 一般 / 知识点: 模拟
POJ 3239 -- Solution to the n Queens Puzzle