UVa 225:Golygons(DFS)

14 篇文章 0 订阅

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=842&page=show_problem&problem=161

题意:平面上有k个障碍点。从(0,0)点出发,第一次走1个单位,第二次走2个单位,……,第n次走n个单位,恰好回到回到(0,0)。要求只能沿着东南西北方向走,且每次必须转弯 90 (不能沿着同一个方向继续走,也不能后退)。走出的图形可以自交,但不能经过障碍点,如图所示。输入n、k (120,0k50) 和所有满足要求的移动序列(用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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值