Ytu 3013: Queen's question (recursive) __ytu

Source: Internet
Author: User
Tags time limit
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.