紫书搜索 习题7-2 UVA - 225 Golygons 搜索dfs

44 篇文章 0 订阅
41 篇文章 0 订阅

题目链接:

https://vjudge.net/problem/UVA-225

题意:

题解:

枚举每一步的方向 没有想到

字典序可以从一开始找方向就处理掉。
还有多一条剪枝,就是当前位置太远剩余的所有步数都不够回道原点

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
int n,k;
int lim = 105;
int G[240][240],vis[240][240],sum[30];
int v[30]; // 每一步的方向
int ans;
char sign[5] = "ensw";
int dir[4][2] = {{1,0},{0,1},{0,-1},{-1,0}}; // ensw

bool ok(int x,int y,int k,int d){
    for(int i=1; i<=k; i++){
        x += dir[d][0], y += dir[d][1];
        if(G[x+lim][y+lim] == -1) return false;
    }

    if(abs(x)+abs(y) > sum[n]-sum[k]) return false;
    return true;
}

void dfs(int x,int y,int k,int fd){
    if(x==0 && y==0 && k==n+1){
        for(int i=1; i<k; i++)
            printf("%c",sign[v[i]]);
        puts("");
        ans++;
        return ;
    }
    if(k > n) return ;

    for(v[k]=0; v[k]<4; v[k]++){ // 枚举每一步的方向
        if(v[k]==fd || v[k]+fd==3) continue;  // 同向 或者 反向
        if(!ok(x,y,k,v[k])) continue; // 剪枝, 如果碰到街区就不走,并且如果剩下的步数 < (x,y)->(0,0)的步数也不行
        int tx = x + dir[v[k]][0]*k, ty = y + dir[v[k]][1]*k;
        if(!vis[tx+lim][ty+lim]){
            vis[tx+lim][ty+lim] = 1;
            dfs(tx,ty,k+1,v[k]);
            vis[tx+lim][ty+lim] = 0;
        }
    }
}

int main(){
    int T = read();
    sum[0] = 0;
    for(int i=1; i<=20; i++)  sum[i] = sum[i-1]+i;
    for(int cas=1; cas<=T; cas++){
        MS(G); MS(vis); ans=0;
        scanf("%d%d",&n,&k);
        for(int i=0; i<k; i++){
            int u,v; scanf("%d%d",&u,&v);
            G[u+lim][v+lim] = -1;  // 把所有的坐标转换为正
        }
        dfs(0,0,1,-1);
        printf("Found %d golygon(s).\n\n",ans);
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值