洛谷——P1747 好奇怪的遊戲

P1747 好奇怪的遊戲

題目背景

《愛與愁的故事第三彈·shopping》娛樂章。node

調調口味來道水題。ios

題目描述

愛與愁大神坐在公交車上無聊,因而玩起了手機。一款奇怪的遊戲進入了愛與愁大神的眼簾:***(遊戲名被打上了馬賽克)。這個遊戲相似象棋,可是隻有黑白馬各一匹,在點x1,y1和x2,y2上。它們得從點x1,y1和x2,y2走到1,1。這個遊戲與普通象棋不一樣的地方是:馬能夠走「日」,也能夠像象走「田」。如今愛與愁大神想知道兩匹馬到1,1的最少步數,你能幫他解決這個問題麼?數組

輸入輸出格式

輸入格式:spa

 

第1行:兩個整數x1,y1code

第2行:兩個整數x2,y2blog

 

輸出格式:隊列

 

第1行:黑馬到1,1的距離遊戲

第2行:白馬到1,1的距離get

 

輸入輸出樣例

輸入樣例#1:  複製
12 16
18 10
輸出樣例#1:  複製
8 
9

說明

100%數據:x1,y1,x2,y2<=20string

 

bfs

因爲要進行兩遍bfs,數組與隊列記得要清空!

#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define N 110
using namespace std;
bool vis[N][N];
int x1,y1,x2,y2,nx,ny,ans,dis[N][N];
int xx[12]={1,1,2,2,2,2,-1,-1,-2,-2,-2,-2};
int yy[12]={-2,2,-2,-1,1,2,-2,2,-1,1,-2,2};
int read()
{
    int x=0,f=1; char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return  x*f;
}
struct Node
{
    int x,y;
}node,p;
queue<Node>q;
void bfs(int x,int y)
{
    while(!q.empty()) q.pop();
    memset(vis,0,sizeof(vis));
    memset(dis,0,sizeof(dis));
    node.x=x,node.y=y;dis[x][y]=0;
    q.push(node);vis[x][y]=true;
    while(!q.empty())
    {
        p=q.front();q.pop();
        x=p.x,y=p.y;
        if(x==1&&y==1) {ans=dis[x][y];return ;}
        for(int i=0;i<12;i++)
        {
            nx=x+xx[i],ny=y+yy[i];
            if(nx>50||ny>50||nx<1||ny<1||vis[nx][ny]) continue;
            vis[nx][ny]=true;
            dis[nx][ny]=dis[x][y]+1;
            p.x=nx,p.y=ny,q.push(p);
        }
    }
}
int main()
{
    x1=read(),y1=read();
    bfs(x1,y1);printf("%d\n",ans);
    x2=read(),y2=read();
    bfs(x2,y2);printf("%d",ans);
    return 0;
}
相關文章
相關標籤/搜索