UVa 225 Golygons (黄金图型)—短小精悍hhhh

题目链接
题意 一个很酷的旅客 准备用自己的方式丈量城市。从0,0点出发走第一步时步长为1 走第二步时步长为2;并且没走完一步要转90°方向再走下一步。还要避开路障。 然后输出能走回0,0的所有方案 以及方案数
分析 DFS 剪枝

#include<bits/stdc++.h>
using namespace std;
const int v=233;
int n,ans;
int dx[4]={1,0,0,-1},dy[4]={0,1,-1,-0};
int buf[1000][1000];
char ch[4]={'e','n','s','w'},arr[1001];
int judge(int a,int b){//确保每次90°转向;
	if(a==0 || a==3) return b!=0 && b!=3;
	if(a==1 || a==2) return b!=1 && b!=2;
	return 1; 
}
bool safe(int x,int y,int a,int b,int f){//确保路上没有路障;
	while(x!=a || y!=b){
		x+=dx[f];y+=dy[f];
		if(buf[x+v][y+v] >0) return false;
	}
	return buf[x+v][y+v]==0;
}
void DFS(int step,int x,int y,int f){
	if(step>n){
		if(!x && !y){ans++;puts(arr);} 
		return;
	}
	for(int i=0;i<4;i++){
		if(judge(f,i) && safe(x,y,x+step*dx[i],y+step*dy[i],i)){
			arr[step-1]=ch[i];
			buf[x+step*dx[i]+v][y+step*dy[i]+v]=-1;
			DFS(step+1,x+step*dx[i],y+step*dy[i],i);
			buf[x+step*dx[i]+v][y+step*dy[i]+v]=0;
		}
	}
}
int main(void){
	int t,m,x,y;
	cin>>t;
	while(t-- && cin>>n>>m){
		ans=0;
		memset(buf,0,sizeof(buf));
		memset(arr,0,sizeof(arr));
		while(m--){cin>>x>>y; buf[x+v][y+v]=1;}
		if(n==7 || n==8 || n==15 || n==16){// 这里是参考了超级帅气的J1nAB1n9 的剪枝方式 
			DFS(1,0,0,5);
		}
		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、付费专栏及课程。

余额充值