uva225
题意:https://vjudge.net/problem/UVA-225
思路
很显然的dfs+回溯,但是需要减枝,不然会TLE
减枝1:判断当前该点是否已经无法回到原点
减枝2:需要判断一步走完后的点是否已经访问过了(题意中没有说明白)
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const char *bin = "ensw";
const int dx[] = {1, 0, 0, -1};
const int dy[] = {0, 1, -1, 0};
int n;
const int maxn = 230;
const int o = 115;
const int N = 24;
// 妙啊妙啊
const int nxt_dir[5][4] = {{1, 2}, {0, 3}, {0, 3}, {1, 2}, {0, 1, 2, 3}};
const int deg[5] = {2, 2, 2, 2, 4};
int vis[maxn][maxn];
int sum[N]; // 储存从1-N所有步骤总和
int mleft[N];
int path[N];
int cnt;
void dfs(int x, int y, int d, int dir)
{
if (d++ == n)
{
if (x == o && y == o) // 起始点在(o,o)代表(0,0)
{
for (int i = 0; i < n; i++)
{
printf("%c", bin[path[i]]);
}
putchar('\n');
cnt++;
}
return;
}
for (int i = 0; i < deg[dir]; i++)
{
int j = nxt_dir[dir][i];
int nx = x + dx[j] * d, ny = y + dy[j] * d;
if (vis[nx][ny])
continue;
if (abs(nx - o) + abs(ny - o) > mleft[d])
continue;
bool flag = false;
if (j == 0 || j == 3)
{
for (int tx = x + dx[j]; tx != nx; tx += dx[j])
{
if (!~vis[tx][y]) // !=0 不等于0
{
flag = true;
break;
}
}
}
else
{
for (int ty = y + dy[j]; ty != ny; ty += dy[j])
{
if (!~vis[x][ty])
{
flag = true;
break;
}
}
}
if (flag)
continue;
path[d - 1] = j;
vis[nx][ny] = 1;
dfs(nx, ny, d, j);
vis[nx][ny] = 0;
}
}
int main()
{
freopen("./in.txt", "r", stdin);
freopen("./out.txt", "w", stdout);
int t;
scanf("%d", &t);
for (int i = 1; i < N; i++)
{
sum[i] = sum[i - 1] + i;
}
while (t--)
{
int k;
scanf("%d%d", &n, &k);
// 注释里的代码不懂,加上去是没有问题
// 源自:https://www.cnblogs.com/jerryRey/p/4637042.html
// if (((n >> 1) & 1) ^ (n & 1))
// {
// printf("Found 0 golygon(s).\n\n");
// continue;
// }
int tx, ty;
memset(vis, 0, sizeof(vis));
for (int i = 0; i < k; i++)
{
scanf("%d%d", &tx, &ty);
if (abs(tx) < o && abs(ty) < o) // 超过了是不可能遇到障碍点的
vis[tx + o][ty + o] = -1; //表示障碍
}
for (int i = 1; i < n; i++)
{
// 从i-n还有多少步骤
mleft[i] = sum[n] - sum[i];
}
cnt = 0;
dfs(o, o, 0, 4);
printf("Found %d golygon(s).\n\n", cnt);
}
return 0;
}