版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/PR_sc/article/details/76672440
题目链接
题意 一个很酷的旅客 准备用自己的方式丈量城市。从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;
}
J1nAB1n9博客传送门->>J1nAB1n9
恩,聪明的J1nAB1n9同学想到了 如果所走的路线可以拼凑成一个矩形的话 即步长之和可以整除4.那么满足这个条件的n才有可能走回原点。