马走日

【问题描述】

   白龙马被封印在了一座棋盘之中,它在棋盘的格点间进行艰难的“日字”移动。白龙马所处地点和出口的位置每隔一个时辰就会变换,这大大增加了白龙马逃脱的难度...假设白龙马处于A点(x,y) ,唯- -的逃脱出口是点B.那么给定棋盘的行列值m, n,请你编程计算一下出口B点出现在哪些位置时,白龙马能够顺利逃出棋盘迷阵,并以m x n矩阵的形式呈现。注: 如果某一点可以作为出口,输出白龙马逃脱的最少步数,如果不能,输出"-1". 棋盘左上角坐标为(1,1)。

   输入: 第一-行为四个整数,前两个整数m和n(1<m , n<=50),分别表示棋盘有m行n列,后两个整数x和y(1 <=x,y<=50) ,表示白龙马的起点坐标。

  输出: 一个m x n的矩阵,代表白龙马到达矩阵中每一点的最少的步数, 其中"-1”表示不能到达该点。

【样例输入】

  3 3 1 1

【样例输出】

  0 3 2

  3 -1 1

  2 1 4

#include<iostream>
using namespace std;
int m, n, sx, sy, map[51][51], head=1, tail=1; 
// 马走日的8个方向。 
int next[8][2]={{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};

struct node{
    int x, y, step;
} que[2501];

void bfs(int x, int y){
    que[tail].x=x;
    que[tail].y=y;
    que[tail].step=0;
    tail++;
    map[x][y]=0;
    while(head<tail){
        for(int i=0; i<=7; i++){
            int tx=que[head].x+next[i][0];
            int ty=que[head].y+next[i][1];
            if(map[tx][ty]==-1&&tx>=1&&tx<=m&&ty>=1&&ty<=n){
                que[tail].x=tx;
                que[tail].y=ty;
                que[tail].step=que[head].step+1;
                map[tx][ty]=que[tail].step;
                tail++;
            }
        }
        head++;
    }
} 

int main(){
    cin>>m>>n>>sx>>sy;
    for(int i=1; i<=m; i++)
        for(int j=1; j<=n; j++)
            map[i][j]=-1;
    bfs(sx, sy);
    for(int i=1; i<=m; i++){
        for(int j=1; j<=n; j++){
                cout<<map[i][j]<<" ";
        }
        cout<<endl;
    }    
    return 0;
} 

 

posted @ 2022-08-08 11:36  Hi,小董先生  阅读(310)  评论(0)    收藏  举报