74pts|12和13时间复杂度炸了,蒟蒻来求助大佬了

P1219 [USACO1.5] 八皇后 Checker Challenge

Smithespics @ 2023-03-11 09:08:54


#include<iostream>
using namespace std;
int n;
int sx,sy;
int cnt = 0;
int len = 0;
int path[15];
int st[15][15];
int dx[8] = {1,0,-1,0,1,1,-1,-1};
int dy[8] = {0,1,0,-1,1,-1,1,-1};

void tag(int x,int y)
{
    st[x][y] = 1;
    for(int i = 0;i < 8;i++)
    {
        for(int j = 1;j <= n;j++)
        {
            sx = x+j*dx[i];
            sy = y+j*dy[i];
            if(sx <= n && sx >= 1 && sy <= n && sy >=1)
                st[sx][sy] = 1;
        }
    }
}

//通过目前path路径存储的皇后所在位置将st数组还原
void tag_1()
{
    for(int i = 1;i <= n;i++)
        for(int j = 1;j <= n;j++)
            st[i][j] = 0;

    for(int i = 0;i < len;i++)
    {
        tag(i+1,path[i]);
    }
}

void dfs(int m)
{
    if(len == n)
    {
        cnt++;
        if(cnt <= 3)
        {
            for(int i = 0;i < n;i++)
                cout << path[i] << ' ';
            cout << endl;
        }
        return;
    }
    else
    {
        for(int i = 1;i <= n;i++)
        {
            if(!st[m][i])
            {
                path[len++] = i;
                tag(m,i);
                dfs(m+1);
                path[--len] = 0;
                tag_1();
            }
        }
    }
}

int main()
{
    cin >> n;
    dfs(1);
    cout << cnt;
    return 0;
}

by Smithespics @ 2023-03-16 13:45:38

@Smithespics 已解决


|