中国象棋中的跳马问题

bfs入门题,不多说,直接看下图的提示吧


#include<bits/stdc++.h>
using namespace std;
int vis[105][105];
int p,k,n;
int x2,y2,m,ans;
int dir[8][2]= {{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1},{-2,1},{-2,-1}};
struct node
{
    int x,y;
    int step;
};
void bfs(int x,int y)
{
    vis[x][y]=1;
    queue<node>q;
    node t;
    t.x=x,t.y=y,t.step=0;
    q.push(t);
    while(!q.empty())
    {
        node temp=q.front();
        q.pop();
        if(temp.x==x2&&temp.y==y2)
        {
            ans=temp.step;
            break;
        }
        for(int i=0; i<8; i++)
        {
            int newx=dir[i][0]+temp.x;
            int newy=dir[i][1]+temp.y;
            if(newx<=0||newx>p||newy<=0||newy>k)
                continue;
            if(vis[newx][newy]!=0)
                continue;
            if((dir[i][0]==-1||dir[i][0]==1)&&dir[i][1]==-2)
            {
                if(vis[temp.x][temp.y-1]==-1)
                    continue;
            }
            if((dir[i][1]==-1||dir[i][1]==1)&&dir[i][0]==-2)
            {
                if(vis[temp.x-1][temp.y]==-1)
                    continue;
            }
            if((dir[i][0]==-1||dir[i][0]==1)&&dir[i][1]==2)
            {
                if(vis[temp.x][temp.y+1]==-1)
                    continue;
            }
            if((dir[i][1]==-1||dir[i][1]==1)&&dir[i][0]==2)
            {
                if(vis[temp.x+1][temp.y]==-1)
                    continue;
            }
            vis[newx][newy]=1;
            node e;
            e.x=newx,e.y=newy,e.step=temp.step+1;
            q.push(e);
        }
    }
}
int main()
{
    int a,b,x1,y1;
    while(scanf("%d",&n)==1)
    {
        while(n--)
        {
            scanf("%d%d",&p,&k);
            memset(vis,0,sizeof(vis));
            scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
            scanf("%d",&m);
            ans=999999999;
            while(m--)
            {
                scanf("%d%d",&a,&b);
                vis[a][b]=-1;
            }
            bfs(x1,y1);
            if(ans==999999999)
                printf("can not reach!\n");
            else
                printf("%d\n",ans);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41061455/article/details/80552731
今日推荐