首页 > 代码库 > UVA - 225 Golygons

UVA - 225 Golygons

题意:求从原点开始依次走1,2...n步后到回到原点的方案数,其中不能经过障碍,每次必须左右拐

思路:一个比较简单的DFS,结果做了好久

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;

const int MAXN = 250;
const int Add = 100;

int n, ans;
int G[MAXN][MAXN], step[MAXN], sum[MAXN];
int dx[4]={1, 0, 0, -1};
int dy[4]={0, 1, -1, 0};
char sign[5]="ensw";

bool check(int x, int y, int d, int k) {
	for (int i = 1; i <= k; i++) {
		x += dx[d];
		y += dy[d];
		if (abs(x) > Add || abs(y) > Add)
			continue;
		if (G[x+Add][y+Add] == -1)
			return true;
	}
	if (abs(x)+abs(y) > sum[20] - sum[k])
		return true;
	return false;
}

void dfs(int x, int y, int cnt, int last) {
	if (cnt > n) {
		if (x == 0 && y == 0) {
			for (int i = 1; i <= n; i++)
				printf("%c", sign[step[i]]);
			printf("\n");
			ans++;
		}
		return;
	}
	int &i = step[cnt];
	for (i = 0; i < 4; i++) {
		if (i == last || i+last == 3)
			continue;
		if (check(x, y, i, cnt))
			continue;
		int nx = x + dx[i]*cnt;
		int ny = y + dy[i]*cnt;
		if (G[nx+Add][ny+Add])
			continue;
		G[nx+Add][ny+Add] = 1;
		dfs(nx, ny, cnt+1, i);
		G[nx+Add][ny+Add] = 0;
	}
}

int main() {
	sum[0] = 0;
	for (int i = 1; i <= 20; i++)	
		sum[i] = sum[i-1] + i;
	int t, k;
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d", &n, &k);
		memset(G, 0, sizeof(G));
		ans = 0;
		for (int i = 0; i < k; i++) {
			int a, b;
			scanf("%d%d", &a, &b);
			if (abs(a) > Add || abs(b) > Add)
				continue;
			G[a+Add][b+Add] = -1;
		}
		dfs(0, 0, 1, -1);
		printf("Found %d golygon(s).\n\n", ans);
	}
	return 0;
}