再帰八皇后復習

983 ワード

#include <bits/stdc++.h>

using namespace std;
#define maxn 20

int map[maxn][maxn];
bool vis[3][2*maxn];
int ans, C[maxn];
int N;
int tot;

void print()
{
    printf(" %d     : ", ++tot);
    for(int i=0; i<N; i++)
       cout<<C[i]+1<<" ";
       cout<<endl;
}

void solve(int cnt)
{
    if(cnt == N)
     print();
    else
    {
        for(int i=0; i<N; i++)
        {
            if(!vis[0][i] && !vis[1][cnt+i] && !vis[2][cnt-i+N])
            {
                vis[0][i] = vis[1][cnt+i] = vis[2][cnt-i+N] = true;
                C[cnt] = i;
                solve(cnt + 1);
                vis[0][i] = vis[1][cnt+i] = vis[2][cnt-i+N] = false;
            }
        }
    }
}


int main()
{
    while(cin>>N && N)
    {
        tot = 0;
        memset(vis, false, sizeof(vis));
        solve(0);
        printf("   %d     
", tot); } return 0; }