蓝桥杯2016初赛

这个是直接暴力写的,但是我想到暴力,但是看了这个博主写的我觉得我肯定会有细节漏掉
https://blog.csdn.net/u014552756/article/details/50946108?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.channel_param

思路

DFS。答案是1580。

代码

这个链接下的暴力方法不超时。
https://blog.csdn.net/u014552756/article/details/50946108

(我这个代码超时,但是运行出来的答案是正确的,直接答案提交就行)

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f

int a[5][5]; // 可以填进去数的地方
int num[5][5]; //填上数
int ans; // 几种填法
bool book[25];
int to[8][2]= {{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0}};

void dfs(int id)
{
    int x=id/4,y=id%4;
    if(x==3)
    {
        bool flag=0;
        for(int i=0; i<3; i++)
        {
            for(int j=0; j<4; j++)
            {
                if(a[i][j]==0) // 判断四周有没有方格
                    continue;
                for(int k=0; k<8; k++) // 八方向
                {
//                    int tx=x+to[k][0];
//                    int ty=y+to[k][1];
                    int tx=i+to[k][0];
                    int ty=j+to[k][1];
                    if(tx>=0&&tx<3&&ty>=0&&ty<4&&a[tx][ty])
                    {
                        if(abs(num[tx][ty]-num[i][j])==1)
                            flag=1;
                    }
                }
            }
        }
        if(!flag) ans++;
        return ;
    }
    if(!a[x][y])
        dfs(id+1);
    else
    {
        for(int i=0; i<=9; i++) // 遍历九个数字
        {
            if(!book[i])
            {
                book[i]=1;
                num[x][y]=i;
                dfs(id+1);
                book[i]=0;
            }
        }
    }
}

int main()
{
//    cout<<1580<<endl; 数字不重复
    ios::sync_with_stdio(false);
    ans=0;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<4; j++)
            a[i][j]=1;
    }
    a[0][0]=0,a[2][3]=0;
    dfs(0);
    cout<<ans<<endl;
    return 0;
}