Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move knights from on

该博客讨论了一种常见的图遍历算法——BFS(广度优先搜索),在处理网格问题时可能遇到的问题。作者通过一个C++实现的BFS示例,展示了如何从起点到终点寻找最短路径。然而,他们指出,如果没有考虑到无法到达目标节点的情况,可能会导致输出为空。为避免这种情况,代码中必须包含适当的错误处理,即当无法找到路径时返回特定值。
摘要由CSDN通过智能技术生成

题目

用bfs搜的时候,没想到会有到达不了的情况 于是造成输出为空的情况

#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <map>
#include <utility>   //pair
#include <string.h>
#include <algorithm>    // 算法
#include <numeric>    // 算法
#include <functional>    // 算法
#include <iostream>
#include <stdio.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pr;
void clear(queue<pr>& q) {
    queue<pr> empty;
    swap(empty, q);
}
int bfs(pr a,pr b,int l) {
    queue<pr> q;
    int d[305][305], v[305][305];
    pr dt[8];
    dt[0] = make_pair(1, 2);
    dt[1] = make_pair(1, -2);
    dt[2] = make_pair(2, 1);
    dt[3] = make_pair(2, -1);
    dt[4] = make_pair(-1, 2);
    dt[5] = make_pair(-1, -2);
    dt[6] = make_pair(-2,1);
    dt[7] = make_pair(-2, -1);
    clear(q); memset(d, 0,sizeof(d)); memset(v, 0,sizeof(v));
    q.push(a);
    d[a.first][a.second] = 0; v[a.first][a.second] = 1;
    while (q.size()) {
        pr c = q.front();
        if (b == c) {
            return d[c.first][c.second];
        }
        q.pop();
        for (int i = 0; i < 8; i++) {
            int newx = c.first + dt[i].first;
            int newy = c.second + dt[i].second;
            if (newx >= 0 && newx < l && newy >= 0 && newy < l && v[newx][newy] == 0) {
                q.push(make_pair(newx, newy));
                d[newx][newy] = d[c.first][c.second] + 1;
                v[newx][newy] = 1;
            }
        }

    }
    return 0;      //非常容易遗漏
}
int main()
{
    int t; cin >> t;
    while (t--) {
        int l; cin >> l;
        int sx, sy, ex, ey; cin >> sx >> sy >> ex >> ey;
        pr s, e; s = make_pair(sx, sy); e = make_pair(ex, ey);
        cout<<bfs(s,e,l)<<endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值