POJ 2488A Knight's Journey(BFS水题)

POJ 2488

题目大意

给出一个国际棋盘的大小,判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径。

注意

有两点注意:
1:路径需要按字典序输出
2:每组数据末尾有一行空行

代码

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<stack>
using namespace std;
const int INF=999999999;
int  T;
int p,q;//p是行数q是列数
int  mat[10][10];
int bj[10][10];
int sum=0;
int xx[9]={0,-2,-2,-1,-1,1,1,2,2};
int yy[9]={0,-1,1,-2,2,-2,2,-1,1};
bool Is_Can(int x,int y)
{
      if(x<=q && x>=1 && y<=p && y>=1)return 1;
      else return 0;
}
struct Node
{
     int x;
     int y;
     Node()
     {
          x=x;y=y;
     }
     Node(int i,int j)
     {
          x=i;y=j;
     }
};
stack<Node> st;
stack<Node>st2;
int Dfs(int x,int y)//x y已被标记
{
      if(sum==q*p)return 1;
      int tx,ty;
      for(int i=1;i<=8;i++)
      {
            tx=x+xx[i];
            ty=y+yy[i];
            if(Is_Can(tx,ty) && bj[tx][ty]==0)
            {
                  bj[tx][ty]=1;
                  sum++;
                  st.push(Node(tx,ty));
                  if(sum==q*p)return 1;
                  Dfs(tx,ty);
                  if(sum==q*p)return 1;
                  st.pop();
                  sum--;
                  bj[tx][ty]=0;
            }
      }
      return -1;
}
int main()
{
    int Case=0;
    cin>>T;
    int t;
    while(T--)
    {
          sum=0;
          Node temp;
          memset(bj,0,sizeof(bj));
          memset(mat,0,sizeof(mat));
          while(!st.empty())st.pop();
          while(!st2.empty())st2.pop();
          cin>>p>>q;
          bj[1][1]=1;
          st.push(Node(1,1));
          sum++;
          t=Dfs(1,1);
          printf("Scenario #%d:\n",++Case);

          if(t!=-1)
          {
                while(!st.empty())
                {
                    st2.push(st.top());
                    st.pop();
                }
                while(!st2.empty())
                {
                    temp=st2.top();
                    st2.pop();
                    cout<<(char)(temp.x-1+(int)'A')<<temp.y;
                }
                cout<<endl;
          }
          else printf("impossible\n");
          cout<<endl;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值