DFS | 2488 | 跳马

WA了很多次。

2488 A Knight's Journey

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

#define MAX 30

bool visit[MAX][MAX], tag;
int dir[8][2] = { {-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1} };
int n, p, q;
char path[MAX][2];

bool is_leagal(int x, int y)
{
    if (x < 1 || x > q || y < 1 || y > p)
        return false;
    if (visit[x][y])
        return false;
    return true;
}

void dfs(int x, int y, int step)
{
    if (step == p * q) {
        tag = true;
        return;
    }

    int temp_x, temp_y;
    for(int i = 0; i < 8; ++i) {
        temp_x = x + dir[i][0];
        temp_y = y + dir[i][1];

        if (is_leagal(temp_x, temp_y))
        {
            path[step][0] = temp_x + 'A' - 1;
            path[step][1] = temp_y + '0';
            visit[temp_x][temp_y] = true;
            dfs(temp_x, temp_y, step + 1);
            if (tag) return;
            visit[temp_x][temp_y] = false;
        }
    }
}

int main()
{
    while (scanf("%d", &n) != EOF) {
        for(int i = 0; i < n; ++i) {
            scanf("%d%d", &p, &q);
            memset(path, 0, sizeof(path));
            memset(visit, false, sizeof(visit));

            tag = false;
            visit[1][1] = 1;
            path[0][0] = 'A';
            path[0][1] = '1';

            printf("Scenario #%d:\n", i + 1);
            dfs(1, 1, 1);
            if (tag) {
                for(int j = 0; j < p * q; ++j)
                    printf("%c%c", path[j][0], path[j][1]);
            }
            else
                printf("impossible");
            printf("\n\n");
        }
    }
}
1,结尾一个换行两个换行都可以过。

2,y是q,是字母,x是p,是数字

3,字典序,从小到大。

DFS的基础题,WA了很多次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值