POJ_1915_KnightMoves

来源:互联网 发布:手机淘宝网触屏版官网 编辑:程序博客网 时间:2024/05/01 04:08

bfs

就是跟马的运动方式一样么……

#include <iostream>#include <stdio.h>#include <queue>using namespace std;const int M=305;int isu[M][M];int dx[8]={-2,-1,1,2,2,1,-1,-2};int dy[8]={-1,-2,-2,-1,1,2,2,1};queue<int>re;int tot;void bfs(int sx,int sy,int ex,int ey,int n){    while(!re.empty())        re.pop();    re.push(sx*n+sy);    isu[sx][sy]=1;    while(!re.empty())    {        int t=re.front();        re.pop();        int cx=t/n,cy=t%n;        //cout<<tot<<" "<<cx<<" "<<cy<<endl;        for(int i=0;i<8;i++)        {            int x=cx+dx[i],y=cy+dy[i];            if(0<=x&&x<n&&y>=0&&y<n&&!isu[x][y])            {                isu[x][y]=isu[cx][cy]+1;                re.push(x*n+y);                if(x==ex&&y==ey)                {                    tot=isu[x][y];                    return;                }            }        }    }}void clear(){    for (int i = 0; i < M;i++)    for (int j = 0; j < M; j++)        isu[i][j] = 0;}int main(){    int t;    int n,xj,yj,xm,ym;    scanf("%d",&t);    while (t--)    {        tot=0;        scanf("%d%d%d%d%d", &n,&xj,&yj,&xm,&ym);        if(xj==xm&&yj==ym)        {            printf("0\n");            continue;        }        clear();        bfs(xj,yj,xm,ym,n);        printf("%d\n", tot-1); //因为不算起点    }    return 0;}


0 0
原创粉丝点击