poj1915--Knight Moves(DFS)

在正方形的矩阵中,可以向8个方向移动,给出起点和终点,求出最快到达终点的步数。

#include<stdio.h>
#include<string.h>
typedef struct{
    int x;
    int y;
    int step;
}point;
typedef struct{
    point a[90000];
    int rear;
    int front;
}queue;
int vis[401][401]={0};
queue q;
int m,n,t,l;
int next[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};   //8种方向
int bfs(int x,int y,int c){
    q.rear=q.front=0;
    q.a[q.rear].x=x;
    q.a[q.rear].y=y;
    q.a[q.rear].step=0;
    q.rear++;                                                               //开始进队
    while(q.front<q.rear){
        point temp=q.a[q.front++];                         //出队
        if(temp.x==m&&temp.y==n) return temp.step;
        for(int i=0;i<8;i++){
            if(temp.x+next[i][0]>=0&&temp.x+next[i][0]<c&&temp.y+next[i][1]>=0&&temp.y+next[i][1]<c&&vis[temp.x+next[i][0]][temp.y+next[i][1]]==0){ //防止越界,并将已经走过的点忽略
                point ttemp;                     //存放下一步的点
                ttemp.x=temp.x+next[i][0];
                ttemp.y=temp.y+next[i][1];
                ttemp.step=temp.step+1;       //下一步进队
                q.a[q.rear++]=ttemp;
                vis[ttemp.x][ttemp.y]=1;
                if(ttemp.x==m&&ttemp.y==n)
                    return ttemp.step;
            }    
        }
    }
}
int main(){
    scanf("%d",&t);
    while(t--){
        int time;
        memset(vis,0,sizeof(vis));
        scanf("%d",&l);
        int q,s;
        scanf("%d%d",&q,&s);
        scanf("%d%d",&m,&n);
        time=bfs(q,s,l);
        printf("%d
",time);

    }
}