poj2488——A Knight's Journey

题目大意:国际象棋的棋盘行为数字(1、2、3...),列为字母(A、B、C...),骑士按照国际象棋马的规则走(走一步意味着在一个方向上跳两格,再在垂直方向上跳一格),问骑士能不能每个格子遍历一次走完整个棋盘,如果有多种路径解法,按字典序最小的输路径,如果无解,则打印impossible

输入:case个数n

           第i个棋盘的行数p 列数q(1<=p*q <= 26)

输出:Scenario #i:

           路径(棋盘每个位置的方块用一个大写字母和一个数字表示)/impossible

           (每组结果之间有一行空行)

分析:dfs搜索

           题目要求字典序最小,由于要求每个格子都走一遍,所以从A1开始搜索,dfs搜索八个方向,按字典序最小的方向循环搜索

代码:

#include<cstdio>
#include<cstring>
using namespace std;
int dx[8] = {-1, 1, -2, 2, -2, 2, -1, 1}; 
int dy[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
struct node{
    int x,y;
}path[27];
int p,q;
bool flag;
char s,t;
bool vis[27][27];
void DFS(int x,int y,int step);
int main(){
    int n;
    scanf("%d",&n);
    for(int cases = 1;cases <= n;cases++){
        scanf("%d %d",&p,&q);
        flag = false;
        memset(vis,false,sizeof(vis));
        vis[1][1] = true;
        DFS(1,1,1);
        printf("Scenario #%d:\n", cases);
        if(flag){
            for (int i = 1; i <= p * q; i++){
                s = path[i].x + '0';
                t = path[i].y + 'A' - 1;
                printf("%c%c", t, s);
            }
            printf("\n");
        }
        else{
            printf("impossible\n");
        }
        if(cases != n)
            printf("\n");
    }
    return 0;
}
void DFS(int x,int y,int step){
    path[step].x = x;
    path[step].y = y;
    if(step == p * q){
        flag = true;
        return;
    }
    for(int i = 0;i < 8;i++){
        int nx = x + dx[i];
        int ny = y + dy[i];
        if(nx > 0 && nx <= p && ny > 0 && ny <= q && !vis[nx][ny] && !flag){
            vis[nx][ny] = true;
            DFS(nx,ny,step + 1);
            vis[nx][ny] = false;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值