poj 2488 A Knight's Journey 水DFS

传送门:poj 2488 A Knight’s Journey

题目大意

有一个p*q的棋盘,有一个棋子只能走日字形,请问这个棋子能遍历完这个棋盘么,
行是按照大写字母的顺序也就是A,B。。。一直有p个
列是按照数字的顺序也就是1,2,。。。q 有q个
如果能遍历完这个棋盘输出遍历的路径。
如果不能输出impossible
输出的格式按照题目中给定的

解题思路

简单地DFS也没有什么坑

#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 200005;
#define lson left,mid,rt<<1
#define rson mid+1,right,rt<<1|1
int path[25][2];
int vis[25][25];
int p,q;
bool flag;
int dirX[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
int dirY[8] = {-2, -2, -1, -1, 1, 1, 2, 2};


void dfs(int row,int col,int step)
{
    path[step][0] = row;
    path[step][1] = col;
    if(step ==(p*q))
    {
        //如果遍历完毕,回到主函数输出
        flag = true;
        return ;
    }
    else
    {
        for(int i=0;i<8;i++)
        {
            int tempRow = row + dirX[i];
            int tempCol = col + dirY[i];
            if(!vis[tempRow][tempCol] && tempRow>=1 && tempRow<=p && tempCol >=1 && tempCol<=q && !flag)
            {
                vis[tempRow][tempCol] = true;
                dfs(tempRow,tempCol,step+1);
                vis[tempRow][tempCol] = false;
            }
        }
    }

}

/**
*path[x][0]记录的是x的行位置
*path[x][1]记录的是x的列位置
*/

int main()
{
    int t;
    int cnt = 1;
    scanf("%d",&t);
    while(t--)
    {
        flag = false;
        scanf("%d%d",&p,&q);
        memset(vis,false,sizeof(vis));
        vis[1][1] = true;
        dfs(1,1,1);
        printf("Scenario #%d:\n",cnt++);
        if(flag)
        {
            for(int i=1;i<=p*q;i++)
                printf("%c%d",path[i][1]-1+'A',path[i][0]);
        }
        else
            printf("impossible");
        printf("\n");
        //这也饿算是一个坑,如果不做下面处理的话会出现Presentation Error
        //Presentation Error出现的原因是说明结果已经和,要求的结果相当类似了,就是可能多一些或者少一些空格或者回车
        if(t != 0)
            printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值