题意:平面上有k个障碍点。从(0,0)点出发,第一次走1个单位,第二次走2个单位,……,第n次走n个单位,恰好回到回到(0,0)。要求只能沿着东南西北方向走,且每次必须转弯 90。 (不能沿着同一个方向继续走,也不能后退)。走出的图形可以自交,但不能经过障碍点,如图所示。输入n、k (1≤20,0≤k≤50) 和所有满足要求的移动序列(用news表示北、东、西、南),按照字典序从小到大排列,最后输出移动序列的总数。(本段摘自《算法竞赛入门经典(第2版)》
分析:
直接DFS搜索即可。但是要注意的是每个城市只能经过一次,虽然题目没有说,不加这个限制的话会wa。
代码:
#include <iostream>
#include <algorithm>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <stack>
#include <set>
using namespace std;
const int maxn = 210 + 5, INF = 1e8;
const int dx[] = {1, 0, 0, -1}, dy[] = {0, 1, -1, 0};
const char trans[] = {"ensw"};
int T, ans, n, k, x, y;
int a[maxn << 1][maxn << 1], path[25], v[maxn << 1][maxn << 1];
bool judge(int x, int y, int xx, int yy)
{
if (x == xx)
{
for (int i = min(y, yy); i <= max(y, yy); ++i)
if (a[x][i])
return false;
}
else
{
for (int i = min(x, xx); i <= max(x, xx); ++i)
if (a[i][y])
return false;
}
if (!v[xx][yy])
return true;
return false;
}
void DFS(int x, int y, int deep, int last)
{
if (deep == n)
{
if (x == maxn && y == maxn)
{
++ans;
for (int i = 0; i < deep; ++i)
printf("%c", trans[path[i]]);
printf("\n");
}
return;
}
for (int i = 0; i < 4; ++i)
if (i != last && i + last != 3)
{
int xx = x + dx[i] * (deep + 1);
int yy = y + dy[i] * (deep + 1);
if (judge(x, y, xx, yy))
{
v[xx][yy] = 1;
path[deep] = i;
DFS(xx, yy, deep + 1, i);
v[xx][yy] = 0;
}
}
}
int main()
{
scanf("%d", &T);
for (int C = 0; C < T; ++C)
{
ans = 0;
memset(a, 0, sizeof(a));
scanf("%d%d", &n, &k);
for (int i = 0; i < k; ++i)
{
scanf("%d%d", &x, &y);
a[x + maxn][y + maxn] = 1;
}
DFS(maxn, maxn, 0, -10);
printf("Found %d golygon(s).\n\n", ans);
}
return 0;
}