SDNU OJ 1025 马踏飞燕

该题是一道使用BFS(广度优先搜索)的经典题目(当然如果你不怕麻烦,DFS也是可以的), 思路很简单,用queue存下各个情况每次都判断是否踏到燕子,并且记得记录深度。

Description

无聊的陶陶准备编写一款游戏,名字就叫做“马踏飞燕”,在这款游戏中有个一个100*100的坐标,把马放在任意一个坐标点,再把燕子放在任意一个坐标点,并且燕子不会移动,马只能按照象棋规则走“日”。若4步之内能“踏”到燕子,则成功。笨蛋的陶陶不知道该怎么去写,现在请你帮助他。
走“日”说明:当马的坐标为(5,5)的时候,马下一步可以走的坐标有8个点,分别为(4,3)(6,3)(3,4)(7,4)(3,6)(7,6)(4,7)(6,7)

Input

第一行两个整数,马的起始坐标x,y (0<x,y<100)
第一行两个整数,燕子的坐标m,n (0<m,n<100)

Output

若4步之内能“踏”到燕子,则输出“Y”
若4步之内不能“踏”到燕子,则输出“N”

Sample Input

5 5
7 4

Sample Output

Y
代码如下:

#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>

using namespace std;

int sun[8][2] = {2,1, 2,-1, 1,2, 1,-2, -2,1, -2,-1 ,-1,2, -1,-2};
bool getyan = 0;
bool sec[105][105];
int i, j;
struct horse
{
    int heng;
    int shu;
    int step;
};
void BFS(int x, int y)
{
     queue<horse> GG;
     GG.push(horse{x, y, 0});
     while(!GG.empty()){
        horse m = GG.front();
        GG.pop();
        if(sec[m.heng][m.shu] != 1){
            sec[m.heng][m.shu] = 1;
            if(m.heng == i && m.shu == j){
                getyan = 1;
                break;
            }
            for(int jump = 0;jump < 8;jump++){
                int h = m.heng + sun[jump][0];
                int s = m.shu + sun[jump][1];
                if(h <= 100 && h >= 1 && s <= 100 && s >= 1 && m.step <= 3){
                    GG.push(horse{h, s, m.step + 1});
                }
            }
        }
     }
     while(!GG.empty()) GG.pop();
}
int main()
{
    int a, b;
    while(scanf("%d %d", &a, &b) != EOF){
    scanf("%d %d", &i, &j);
    BFS(a, b);
    if(getyan) cout << 'Y' << endl;
    else cout << 'N' << endl;
    memset(sec, 0, sizeof(sec));
    getyan = 0;
    }
    return 0;
}










猜你喜欢

转载自blog.csdn.net/lxcxingc/article/details/78628967