3013: The Queen question (recursion)Time limit: 1 Sec Memory limit: 128 MB
Submitted: 2 Settlement: 2
Topic Description
Write a function to solve the Queen's problem: on the n*n checkerboard, place n Queens, asking each queen to have different rows, different columns, and different left and right diagonal lines.
Requirements:
1, the number of Queens by the user input, its value can not exceed 20, output all the solutions.
2, using recursive backtracking method to solve.
input
Enter an integer n that represents the size of the chessboard n*n,
Output
All placement scenarios that will be calculated for each of the n queens that are not attacked, one row for each scenario.
Sample Input
4
Sample Output
2 4 1 3 3 1 4 2
Tips
1, the provisions of the search for each row from left to right, each column from the top down search.
2, as far as possible to adopt a more excellent algorithm.
3, using recursive solution.
lost in the valley of the birds, flying alone in this huge world, but do not know where to fly to the side ...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int n,a[20];
int check (int n)
{
int i;
For (i=0 i<n; i++) if (a[i]==a[n]| | Fabs (n-i) ==fabs (a[i]-a[n)) return 0;
return 1;
}
void put (int n)
{
int i;
if (n==n) return;
for (i=0; i<n; i++)
{
a[n]=i;
if (check (n))
{
if (n==n-1) for
(i=0 i<n; i++)
printf (i!=n-1?) %d ":" "%d\n", a[i]+1);
else put (n+1);
}} int main ()
{
scanf ("%d", &n);
Put (0);
return 0;
}