Knight Moves 的解法

#include"stdio.h"
#include"stdlib.h"
#include"malloc.h"
#define MAXQSIZE 5000
typedef struct
{
 int x,y,step;
}Point;
typedef struct
{
 int *base;
 int front,rear;
}SqQueue;

int chess[301][301];

int dire[8][2] = {{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};    //定义马要走的八个方向
int m,beginx,beginy,endx,endy;

//构造队列
int InitQueue(SqQueue &Q)
{
 Q.base = (int *)malloc(MAXQSIZE * sizeof(int));
 if(!Q.base)
  exit(0);
 Q.front=Q.rear=0;
 return 1;

}

//插入元素到队列
int EnQueue(SqQueue &Q,int e)
{
 if((Q.rear+1)%MAXQSIZE == Q.front)
  return 0;
 Q.base[Q.rear]=e;
 Q.rear = (Q.rear+1) %MAXQSIZE;
 return 1;
}

//删除队头元素
int DeQueue(SqQueue &Q,int &e)
{
 if(Q.front==Q.rear)
  return 0;
 e=Q.base[Q.front];
 Q.front = (Q.front+1) % MAXQSIZE;
 return e;
}

//判断队列是否为空
int Empty(SqQueue Q)
{
 if(Q.rear-Q.front==0)
  return 0;
 else
  return 1;
}

int Moves(int x1,int y1)
{
    int x,y,e=0;
   
 SqQueue S;
 InitQueue(S);

 Point begin,temp;

 begin.x=x1;
 begin.y=y1;
 begin.step=0;
       
 EnQueue(S,begin.x);   //把开始位置插入队列;
 EnQueue(S,begin.y);
    EnQueue(S,begin.step);

    chess[x1][y1]=1;
 while(Empty(S))
 {
        temp.x = DeQueue(S,e);          //删除队头元素
  temp.y = DeQueue(S,e);
  temp.step = DeQueue(S,e);
  
       
        for(int i=0;i<8;i++)
  {
   x=temp.x+dire[i][0];
   y=temp.y+dire[i][1];

   if(chess[x][y]==0&&x>=0&&x<m&&y>=0&&y<m)       //判断是否在矩阵内
   {
    
    begin.x=x;
    begin.y=y;
    begin.step = temp.step+1;
    
    chess[x][y]=1;

    if(x==endx&&y==endy)
     return begin.step;
    EnQueue(S,begin.x);              //插入队列
    EnQueue(S,begin.y);
    EnQueue(S,begin.step);

   }
  }

 }


 
}
int main()
{
 int n=0;
 
 scanf("%d",&n);
 while(n--)
 {
  
  scanf("%d",&m);
  if(m>=4&&m<=300)
  {
       // memset(chess, 0, sizeof(chess));
  for(int i=0;i<m;i++)
   for(int j=0;j<m;j++)
    chess[i][j]=0;
  scanf("%d%d%d%d",&beginx,&beginy,&endx,&endy);
  if(beginx==endx&&beginy==endy)
  { 
   
   printf("0/n"); 
  }
   
  else
  {
   
                      printf("%d/n",Moves(beginx,beginy));
     
  }
  }
 
  
 }
 

 return 1;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值