poj 1915/2243 bfs(马走日)

本文介绍如何使用BFS算法解决给定棋盘上从起点到终点的最少步数问题,具体针对马走日的走法进行求解。

题意:给定一个n*n的棋盘,一个起点坐标,一个终点坐标。问从起点“走日”到终点的最少步数。走日即象棋里的马走日。(2243题意完全相同,只不过棋盘限制在8*8)

思路:bfs水题。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cstdlib>
using namespace std;
#define clc(s,t) memset(s,t,sizeof(s))
#define INF 0x3fffffff
#define N 305
int s[N][N],flag[N][N];
int T,n;
int a,b,x,y;
int ori[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
struct node{
    int x,y,t;
    node(int xx,int yy,int tt):x(xx),y(yy),t(tt){};
};
queue<struct node>q;
int check(int x,int y){
    return x>=0&&y>=0&&x<n&&y<n;
}
int bfs(){
    while(!q.empty()){
        struct node now = q.front();
        q.pop();
        if(now.x == x && now.y == y)
            return now.t;
        for(int i = 0;i<8;i++){
            int xx = now.x+ori[i][0];
            int yy = now.y+ori[i][1];
            if(check(xx, yy) && !flag[xx][yy]){
                q.push(node(xx,yy,now.t+1));
                flag[xx][yy] = 1;
            }
        }
    }
    return -1;
}
int main(){
    scanf("%d",&T);
    while(T--){
        while (!q.empty())
            q.pop();
        clc(flag, 0);
        scanf("%d",&n);
        scanf("%d %d %d %d",&a,&b,&x,&y);
        q.push(node(a,b,0));
        flag[a][b] = 1;
        printf("%d\n",bfs());
    }
    return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值