poj2488---A Knight's Journey

转载请注明出处

图的遍历算法---DFS(深度优先+递归+回退)

注意:1.书写DFS函数式,首先对该点进行标记chess[x][y]=true,并把位置用way[deep].row和way[deep].col记录,然后对该点所有可能的下一点进行遍历+回退

2.字典序,确保第一点为A1,对每点扫描的时候也按照字典的先后顺序进行di[8]和dj[8].

/********************Invented by Hacker_vision******************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e3+10;
bool chess[30][30];
bool flag;
int step;
int p,q;
int di[8]={-1,1,-2,2,-2,2,-1,1};
int dj[8]={-2,-2,-1,-1,1,1,2,2};//对字典序的理解要正确呦
struct node
{
  int row;
  char col;
}way[30];
void dfs(int x,int y,int deep)
{
    chess[x][y]=true;
    way[deep].row=x;way[deep].col='A'+y-1;//先标记再遍历
    if(deep==step) {
    flag=true;
    return;
    }
    for(int i=0;i<8&&flag==false;i++){
        int pos_x=x+di[i];
        int pos_y=y+dj[i];
        if(pos_x>=1&&pos_x<=p&&pos_y>=1&&pos_y<=q&&chess[pos_x][pos_y]==false){
            dfs(pos_x,pos_y,deep+1);//向下遍历
            chess[pos_x][pos_y]=false;//回退
        }
    }
    return;
}
int main(void)
{
   // freopen("input.txt","r",stdin);
    int T;cin>>T;
    int count=0;
    while(T--){
      cin>>p>>q;
      cout<<"Scenario #"<<++count<<":"<<endl;
      memset(chess,false,sizeof(chess));
      step=p*q;
      flag=false;
    //  way[1].row=1,way[1].col='A';
      dfs(1,1,1);
      if(flag==false) cout<<"impossible"<<endl<<endl;
     else{
        for(int i=1;i<=step;++i)
        cout<<way[i].col<<way[i].row;
        cout<<endl<<endl;
       }
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值