N Queen's question
Time limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 11388 Accepted Submission (s): 5059
Problem description placed n Queens on the N*n's checkered chessboard, making them not attack each other (that is, any 2 queens are not allowed to be in the same row, in the same column, or in a diagonal line with a 45-angle checkerboard border.)
Your task is to find out how many legal placement methods are available for a given n.
Input has several lines, one positive integer n≤10 per line, indicating the number of boards and queens, or, if n=0, the end.
Output has several rows, one positive integer per line, representing the number of different placements of the queen corresponding to the input row.
Sample Input
1850
Sample Output
19210
Problem: N Queen is a classic deep search topic but the problem is that if you go deep into it, it will be tle. My idea is that since every row in each column is bound to have a queen, you can record the Queen in each column. After which row, a check function is passed to determine if the Queen is in conflict with the current or current column or slash direction
Finally, if there is no conflict and every column has a queen, it is possible to place the scheme ++ans finally search all the results
But in fact, this method is optimized, but I'll get the tle code for the tle .
#include <cstdio> #include <cstring>int ans, n;int an[11];bool check (int k); void Dfs (int k); int main () { while (scanf ("%d", &n)! = EOF && N) { memset (an, 0, sizeof (an)); Ans = 0; DFS (1); printf ("%d\n", ans); } return 0;} BOOL Check (int k) {for (int i = 1; i < K; ++i) { if (an[k] = = An[i] | | an[k]-an[i] = = K-i | | an[k]-an[i] = = i-k) { return false; } } return true;} void Dfs (int k) { if (k = = n+1) { ++ans; return; } for (int i = 1; I <= n; ++i) { an[k] = i; if (check (k)) { DFS (k+1);}} }
So I added a small optimization first to find out all the number of scenarios with an array of storage and then select the corresponding value output from the array according to the input
Here is the AC code
#include <cstdio> #include <cstring>int sum, n; n as input int ans[11], an[11]; Ans Storage Scheme number an a row bool check (int k) of the Queen where the corresponding column is stored; Check function void dfs (int k); The deep search function int main () { for (int i = 1; i <; ++i) { //////////////) First calculate the corresponding scheme number n = I;memset (an, 0, sizeof); sum = 0; Each time the initial value is assigned DFS (1); ans[i] = sum; Store the corresponding scheme number} while (scanf ("%d", &n)! = EOF && N) { printf ("%d\n", Ans[n]); } return 0;} BOOL Check (int k) {for (int i = 1; i < K; ++i) { if (an[k] = = An[i] | | an[k]-an[i] = = K-i | | an[k]-an[i] = = i-k) { return false; } } return true;} void Dfs (int k) { if (k = = n+1) { ++sum; return; } for (int i = 1; I <= n; ++i) { an[k] = i; if (check (k)) { DFS (k+1);}} }
"HDU2553" n Queen question