pku1915

/*
给你一个n*n的棋盘,以及一个出发点和终点,按照国际象棋的马的走法,要你算出从出发点到终点用的最少的步数。
思路:用广度优先搜索法,某个点出发可以有8个方向,若某个方向的点可达且不是终点,则进队列,然后取对头元素
重复上述步骤。直到找到终点。
*/

#include<iostream>
#include<queue>
using namespace std;
#define L 305

struct node {
    int x, y;
    int num;
};
node start, end;
int x[8][2] = {
    {-2, -1},
    {-1, -2},
    {1, -2},
    {2, -1},
    {2, 1},
    {1, 2},
    {-1, 2},
    {-2, 1}
};
bool visited[L][L];
int a[L][L], n, ans;
bool OK;
void BFS() {
    int i, j;
    node pos, next;
    queue<node>q;
    q.push(start);
    while (!q.empty()) {
        if(OK)break;
        pos = q.front();
        q.pop();
        for (i = 0; i < 8; i++) {
            if(OK)break;
            next.x = pos.x + x[i][0];
            next.y = pos.y + x[i][1];
            next.num=pos.num+1;
            if (next.x >= 0 && next.x < n && next.y >= 0 && next.y < n&&a[next.x][next.y] == 0) {
                    a[next.x][next.y] = 1;
                    if (next.x == end.x && next.y == end.y) {
                        end.num=next.num;
                        OK=1;
                    }
                    q.push(next);
            }
        }
    }
}

int main() {

    int t, i, j, k;
    cin >> t;
    while (t--) {
        cin >> n;
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                a[i][j] = 0;
            }
        }
        cin >> start.x >> start.y;
        start.num=0;
        a[start.x][start.y] = 1;
        cin >> end.x >> end.y;
        if (start.x == end.x && start.y == start.y) {
            cout << "0" << endl;
            continue;
        }
        OK=0;
        BFS();
        cout<<end.num<<endl;
    }
    system("pause");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值