洛谷 P1746:离开中山路 ← BFS

【题目来源】
https://www.luogu.com.cn/problem/P1746

【题目描述】
爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在 x1,y1 处,车站在 x2,y2 处。现在给出一个 n×n(n≤1000) 的地图,0 表示马路,1 表示店铺(不能从店铺穿过),爱与愁大神只能垂直或水平着在马路上行进。爱与愁大神为了节省时间,他要求最短到达目的地距离(每两个相邻坐标间距离为 1)。你能帮他解决吗?

【输入格式】
第 1 行包含一个数 n。
第 2 行到第 n+1 行:整个地图描述(0 表示马路,1 表示店铺,注意两个数之间没有空格)。
第 n+2 行:四个数 x1,y1,x2,y2。

【输出格式】
只有 1 行,即最短到达目的地距离。

【输入样例】
3
001
101
100
1 1 3 3

【输出样例】
4

【数据范围】
对于 20% 数据,满足 1≤n≤100。
对于 100% 数据,满足 1≤n≤1000。

【算法分析】
BFS算法助记:建-入-量:头-出-入,详见:
https://blog.csdn.net/hnjzsyjyj/article/details/125801217

【算法代码】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

typedef pair<int,int> PII;
const int N=1e3+5;
char g[N][N];
int dis[N][N];
int dx[]= {-1,0,1,0};
int dy[]= {0,1,0,-1};
int n,m;

int bfs(int sx,int sy,int ex,int ey) {
    memset(dis,-1,sizeof dis);
    dis[sx][sy]=0;

    queue<PII> q;
    q.push({sx,sy});
    while(!q.empty()) {
        int x=q.front().first;
        int y=q.front().second;
        q.pop();
        if(x==ex && y==ey) return dis[x][y];
        for(int i=0; i<4; i++) {
            int tx=x+dx[i];
            int ty=y+dy[i];
            if(tx>=0 && tx<n && ty>=0 && ty<m) {
                if(g[tx][ty]!='1' && dis[tx][ty]==-1) {
                    dis[tx][ty]=dis[x][y]+1;
                    q.push({tx,ty});
                }
            }
        }
    }
    return -1;
}

int main() {
    cin>>n;
    m=n;
    for(int i=0; i<n; i++) {
        cin>>g[i];
    }

    int sx,sy,ex,ey;
    cin>>sx>>sy>>ex>>ey;
    sx--,sy--,ex--,ey--;
    cout<<bfs(sx,sy,ex,ey)<<endl;
    return 0;
}

/*
in:
3
001
101
100
1 1 3 3

out:
4
*/

【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/158773523

相关推荐
froyoisle3 小时前
CSP 真题解析:[CSP-J 2019-T4] 加工零件
c++·算法·bfs·csp-j·算法竞赛·信息学·信奥赛
汉克老师7 天前
GESP2026年6月认证C++七级( 第一部分选择题(8-15))精讲
c++·dfs·bfs·哈希·二分算法·gesp7级·网格dp
拳里剑气8 天前
C++算法:队列与BFS
c++·算法·bfs·宽度优先·队列
硕风和炜9 天前
【LeetCode: 2492. 两个城市间路径的最小分数 + DFS】
java·算法·leetcode·深度优先·dfs·bfs·并查集
小欣加油1 个月前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
小欣加油1 个月前
leetcode542 01矩阵
数据结构·c++·算法·leetcode·矩阵·bfs
进击的荆棘1 个月前
优选算法——队列+宽搜
数据结构·c++·算法·leetcode·bfs·队列
Misnearch2 个月前
1345. 跳跃游戏 IV
java·leetcode·bfs
YL200404262 个月前
041二叉树的层序遍历
数据结构·leetcode·bfs
浅念-2 个月前
LeetCode最短路必看:BFS算法原理+经典题解
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先