Poj2488_深度优先搜索+回溯

基础题,深度优先搜索加回溯,一开始一直runtime error检查了半天发现是自己数组开太小的原因,真是脑抽

#define LOCAL
#include<stdio.h>
#include <string.h>

const int movex[10] = {-2, -2, -1, -1, 1, 1, 2, 2};
const int movey[10] = {-1, 1, -2, 2, -2, 2, -1, 1};
const char Letter[20] = {'1', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'};
int p, q;
int match[30][30];
int last[50][2];
bool flag = false;
int kase;

bool dfs(int x, int y, int lx, int ly)
{
    if (flag == true)
        return false;
    match[x][y] = 1;
    int countt = 0;
    for (int f = 1; f <= q; f++)
    {
        for (int g = 1; g <= p; g++)
        {
            countt += match[f][g];
        }
    }
    last[countt][0] = lx;
    last[countt][1] = ly;
    if (countt == p * q)
    {
        flag = true;
        printf("Scenario #%d:\n", kase);
        for (int c = 2; c <= countt; c++)
        {
            printf("%c%d", Letter[last[c][0]], last[c][1]);
        }
        printf("%c%d", Letter[x], y);
        printf("\n\n");
        return true;
    }

    for (int w = 0; w <= 7; w++)
    {
        int tx = x + movex[w];
        int ty = y + movey[w];
        if (tx <= q && tx >= 1 && ty <= p && ty >= 1 && match[tx][ty] != 1)
        {
            if(dfs(tx, ty, x, y))
                return true;
        }
    }
    match[x][y] = 0;
    return false;
}
int main()
{
#ifdef LOCAL
    freopen("data.in", "r", stdin);
#endif
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d%d", &p, &q);
        kase = i;
        flag = false;

        memset(match, 0, sizeof(match));
        memset(last, 0, sizeof(last));
        dfs(1, 1, 0, 0);

        if (flag == false)
            printf("Scenario #%d:\nimpossible\n\n", kase);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值