1128 N Queens Puzzle (20 分)(O(n)方法)
题目描述:
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 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.
![]() | ![]() | |
---|---|---|
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 Q1 Q2 ... QN", 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
思路:这道题最直接的思路就是创一个二维数组,然后每到一个位置往回三个方向一个一个判断,时间复杂度O(n^2),空间复杂度O(n^2),我第一次做也是这么过的,
但是我们可以发现,每个位置都要从三个方向往回找,如果这三个方向上放着另一个物品,这就不是一个合格的N皇后棋盘,而这三个方向在矩阵的边界点是可以直接求得的
我们每次只需要计算出这三个方向的边界位置,判断该位置放没放点,如果三个边界点都没放,就满足,然后在三个边界点上放上这个点,即标记这三个位置都不能再放了
再进行下一个点的判断,具体实现就是,左上和左下的方向再棋盘上最多有2*n-1个边界位置,中间对齐最多有n个位置,假设当前需要判断的位置是(i,j),位于左下方向的
判断点为i-j+n,位于左上判断点的位置为i+j-1,中间对齐位置就是j,所以就能以O(n)的时间,空间复杂度解决这道题啦,现在想来,N皇后的DFS算法也能用这个优化,
每一行的某一个列能不能取只需要O(1)的复杂度
AC代码:
#include<iostream> #include<string> #include<map> #include<set> #include<algorithm> #include<queue> #include<cmath> #include<string.h> #include<unordered_map> #include<unordered_set> using namespace std; #define INT_MIN -2147483648 #define INT_MAX 2147483647 const int maxn = 1e3 + 1; int read() { char p; while ((p = getchar()) < '0' || p > '9'); int sum = p - 48; while ((p = getchar()) >= '0' && p <= '9')sum = sum * 10 + p - '0'; return sum; } int n,t; int v1[maxn],v2[maxn],v3[maxn]; int main() { t = read(); while (t--) { n = read(); memset(v1, 0, sizeof(v1)); memset(v2, 0, sizeof(v2)); memset(v3, 0, sizeof(v3)); int f = 1; for (int i = 1; i <= n; i++) { int j = read(); int p1 = i - j + n,p2=i+j-1; if (v1[p1] || v2[p2] || v3[j]) {//如果该位置以及放过点了 f = 0; } v1[p1] = v2[p2] = v3[j] = 1; } if (f) { printf("YES\n"); } else { printf("NO\n"); } } return 0; }