您的位置:首页 > 编程语言 > Go语言

UVA225 Golygons 【搜索, dfs】

2017-04-29 20:30 239 查看
题目链接:https://vjudge.net/problem/UVA-225

题意:

一群游客去耍,从0,0点开始,第一次能走1格,后面每次能走比上次多1个格,而且这次走的方向不能与上次一样(如:s和s),也不能和上次相反(如:s和n),也不能穿过障碍物,给出n表示最多走n次,问能有多少种方案数?

题解:

lrj先生的书上的描述是有bug的,mdzz…

坑了我两个多小时呢 QWQ

lrj的书上说可以是自交图形,结果被我理解错了= =注意这里的自交不应该在结点交= =b

其余的就是一个暴力回溯,跑了860ms,并不优秀,但对于3s的时限已经足够了 ..

P.S:注意格式!注意初始化!

代码:

// by DenyTianly
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

const int inf = 1 << 26;

const int pls = 100;
int n;
int con[505][505], d[][2] = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}};
char seq[4] = {'e', 'n', 's', 'w'};
int ans[10005], tot = 0;

void dfs(int x, int y, int cnt) {
if(cnt == n+1) {
if(!x && !y) {
tot ++;
for ( int i = 1; i <= n; i ++ ) printf("%c", seq[ans[i]]);
puts("");
}
return ;
}

for ( int i = 0; i < 4; i ++ ) {
// ensw 0 1 2 3   e->w 3-e --> w   n->s 3-n --> s
if(cnt > 1 && ((ans[cnt-1]/**/ == i) || (ans[cnt-1] == 3-i))) continue;
// 符合下一次走的要求

int fx = x, fy = y;
bool fg = 1;

for ( int j = 1; j <= cnt; j ++ ) {
fx += d[i][0];
fy += d[i][1];
if(abs(fx) > pls || abs(fy) > pls || con[fx+pls][fy+pls] == -1) {
fg = 0;
break;
}
}

if( fg && con[fx+pls][fy+pls] == 0 ) {
con[fx+pls][fy+pls] = 1;
ans[cnt] = i;
dfs(fx, fy, cnt+1);
con[fx+pls][fy+pls] = 0;
}
}
}

int main(){
//  freopen("UVA225.in", "r", stdin);
int test;
scanf("%d", &test);
while( test -- ) {
int p;
memset(con, 0, sizeof(con));
scanf("%d %d", &n, &p);
for ( int i = 0; i < p; i ++ ) {
int x, y;
scanf("%d %d", &x, &y);
con[x+pls][y+pls] = -1;
}

tot = 0;
dfs(0, 0, 1);
printf("Found %d golygon(s).\n\n", tot);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: