bfs例题

该篇文章描述了一个编程问题,涉及使用BFS(广度优先搜索)算法帮助爱与愁大神在给定的地图中,避开店铺,找到从起点到终点的最短路径,路径上相邻坐标间距离为1。
摘要由CSDN通过智能技术生成

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

#include <stdio.h>
#include <stdbool.h>
#define MAX_N 1001
struct Pos {
    int x, y;
};
struct Pos start;
  struct Pos current;
  struct Pos next;
int n, x, y, tx, ty, dis[MAX_N][MAX_N], s_a, s_b, t_a, t_b;
char mp[MAX_N][MAX_N];
bool vis[MAX_N][MAX_N];
struct Pos queue[MAX_N * MAX_N];
int front = 0, rear = 0;

const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
void enqueue(struct Pos p) {
    queue[rear++] = p;
}
struct Pos dequeue() {
    return queue[front++];
}
bool isEmpty() {
    return front == rear;
}

int bfs(int sx, int sy) {
    start.x= sx;
    start.y= sy;
    enqueue(start);
    vis[sx][sy] = true;
    dis[sx][sy] = 0;
    while (!isEmpty()) {
       current=dequeue();
        x = current.x;
        y = current.y;

        if (x == t_a && y == t_b) {
            return dis[x][y];
        }

        for (int i = 0; i < 4; i++) {
            tx = x + dx[i];
            ty = y + dy[i];
            if (tx < 1 || tx > n || ty < 1 || ty > n) continue;
            if (mp[tx][ty] == '1' || vis[tx][ty]) continue;
            dis[tx][ty] = dis[x][y] + 1;
            vis[tx][ty] = true;
            next.x= tx;
            next.y= ty;
            enqueue(next);
        }
    }

    return -1;
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            scanf(" %c", &mp[i][j]);
        }
    }
    scanf("%d %d %d %d", &s_a, &s_b, &t_a, &t_b);

    printf("%d\n", bfs(s_a, s_b));
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值