洛谷 1746.离开中山路

思路:其实你也可以用DFS中那个连通块模板进行做,不需要回溯。但是会略显麻烦,因为数据范围上很大。

一般这样的迷宫问题我们用BFS解决是最好的,这样也省时也好做。

思路:这道题其实就是对于起点和终点进行输入之后,我们再对于起点开始BFS。

变量就是x,y轴。我们运用队列进行实现,也就是逐层遍历,这样的话,我们需要一个距离数组,也就是记录层数,也就是距离起点有多远的问题。

其次,我们需要队列,每一个在队首的我们都需要遍历它的周围是不是有能走的地方,如果有,我们就标记上,在原先的距离上+1,然后我们把距离相等这一层都入队。就这样依次类推即可。

上代码:

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath> 
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<sstream>
#include<numeric>
#include<map>
#include<limits.h>
#include<set>
#define int long long
#define MAX 1010
#define _for(i,a,b) for(int i=a;i<(b);i++)
#define ALL(x) x.begin(),x.end()
using namespace std;
typedef pair<int, int> PII;
int n, m;
int counts;
char maps[MAX][MAX];
int dist[MAX][MAX];
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
queue<PII>q;
int x2, y2;
int bfs(int x, int y) {
    memset(dist, -1, sizeof dist);
    q.push({ x,y });
    while (!q.empty()) {
        auto tmp = q.front();
        q.pop();
        dist[x][y] = 0;
        for (int i = 0; i < 4; i++) {
            int a = dx[i] + tmp.first;
            int b = dy[i] + tmp.second;
            if (a <= 0 || a > n || b <= 0 || b > n)continue;
            if (maps[a][b] != '0')continue;
            if (dist[a][b] > 0)continue;

            q.push({ a,b });
            dist[a][b] = dist[tmp.first][tmp.second]+1;
            if (x == x2 && y == y2)
                return dist[x2][y2];
        }
    }
    return dist[x2][y2];
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> maps[i][j];
        }
    }
    int x1, y1;
    cin >> x1 >> y1 >> x2 >> y2;
    counts=bfs(x1, y1);
    cout << counts;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值