SDNU 1027 马踏飞燕序

这是一道标准的BFS题,先将题目贴一下:

写这道题就当是复习一下BFS吧

Description

上次的马踏飞燕是不是没玩够?无聊的lg准备编写一款游戏,就是加强版的“马踏飞燕”,在这款游戏中有个一个2000*2000的坐标,把马放在任意一个坐标点,再把燕子放在任意一个坐标点,并且燕子不会移动,马只能按照象棋规则走“日”。若200步之内能“踏”到燕子,则成功。lg不知道该怎么去写,现在请你帮助他。
走“日”说明:当马的坐标为(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<2000)
第一行两个整数,燕子的坐标 m,n (0<m,n<2000)

Output

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

Sample Input

5 5
7 4

Sample Output

Y

代码如下:

 

#include <cstdio>  
#include <cstring>  
#include <algorithm>  
#include <iostream>  
#include <cmath>  
#include <queue>  
using namespace std;  
int x, y, n, m, flag;  
int dir[8][2] = {1,2,2,1,1,-2,2,-1,-1,-2,-2,-1,-1,2,-2,1};  
int vis[2005][2005];  
struct node  
{  
    int x, y;  
};  
void bfs(int startx, int starty)  
{  
    queue<node> q;  
    node tem;  
    tem.x = startx;  
    tem.y = starty;  
    q.push(tem);  
    while(!q.empty())  
    {  
        if(flag) return ;  
        node now, nex;  
        now = q.front();  
        q.pop();  
        if(vis[now.x][now.y] <= 199)  //累计步数
        {
		    for(int i = 0; i < 8; ++i)  
            {  
                nex.x = now.x + dir[i][0];  
                nex.y = now.y + dir[i][1];  
                if(nex.x <= 0 || nex.x > 2000 || nex.y <= 0 || nex.y > 2000) 
					continue;  
                if(vis[nex.x][nex.y]) 
					continue;  //这里防止重复访问  
                if(nex.x == m && nex.y == n)  
                {  
                    flag = 1;  
                    return ;  
                }  
                vis[nex.x][nex.y] = vis[now.x][now.y] + 1;  
                q.push(nex);  
            }  
        }
    }  
}  
int main()  
{  
    scanf("%d %d %d %d",&x,&y,&m,&n);  
    flag = 0;  
    bfs(x, y);  
    if(flag==1)  
		cout << "Y" << endl;  
    else 
		cout << "N" << endl;  
    return 0;  
}  

这道题目要注意的一点就是题目中说要在4步之内完成,所以我们需要记录一下步数,这里用的方法是 原步数+1,通过构建结构体来实现,这样子每次向各个方向移动都能分别

记录对应的步数。  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值