码迷,mamicode.com
首页 > 其他好文 > 详细

1128 N Queens Puzzle

时间:2020-04-21 23:40:06      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:test   column   case   位置   present   har   icon   img   图片   

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

标签:test   column   case   位置   present   har   icon   img   图片   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/12748706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!