本文主要是介绍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;
}
这篇关于UVA - 225 Golygons的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!