洛谷——P1746 离开中山路

题目背景

《爱与愁的故事第三弹·shopping》最终章。

题目描述

爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在 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 行,即最短到达目的地距离。

输入输出样例

输入 #1

3
001
101
100
1 1 3 3

输出 #1

4

说明/提示

对于 20% 数据,满足 1≤n≤100。

对于 100% 数据,满足 1≤n≤1000。

代码

#include<bits/stdc++.h>
using namespace std;
int n, bx, by, ex, ey;
char g[1005][1005];
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
struct node {
	int x, y, step;
};
void bfs() {
	queue<node>q;
	q.push(node{ bx,by,0 });
	g[bx][by] = '1';
	while (!q.empty()) {
		node now = q.front();
		q.pop();
		if (now.x == ex && now.y == ey) {
			cout << now.step;
			return;
		}
		for (int i = 0; i < 4; i++) {
			node next = node{ now.x + dx[i],now.y + dy[i],now.step + 1 };
			if (next.x >= 1 && next.x <= n && next.y >= 1 && next.y <= n && g[next.x][next.y] == '0') {
				q.push(next);
				g[next.x][next.y] = '1';
			}
		}
	}
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) cin >> g[i][j];
	}
	cin >> bx >> by >> ex >> ey;
	bfs();
	return 0;
}

AC合格证

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值