P1746 离开中山

题目背景

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

题目描述

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

输入格式

第 11 行包含一个数 �n。

第 22 行到第 �+1n+1 行:整个地图描述(00 表示马路,11 表示店铺,注意两个数之间没有空格)。

第 �+2n+2 行:四个数 �1,�1,�2,�2x1​,y1​,x2​,y2​。

输出格式

只有 11 行,即最短到达目的地距离。

输入输出样例

输入 #1复制

3
001
101
100
1 1 3 3

输出 #1复制

4

说明/提示

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

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

解题思路

因为要求最短的路,我们在bfs里面增加一个找到路就跳出的语句。写bfs要注意队列的数据类型,数据的初始化工作。

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<vector>
#include<math.h>
#include<iomanip>
#include<set>
#include<queue>
#include<stack> 
#include<map>
#include<list>
#include <stdlib.h>
#include<deque>
using namespace std;
int n, m,zx,zy;
typedef pair <int, int>ppi ;
int ans,d[1005][1005],v[1005][1005];
char g[1005][1005];
queue<ppi>qq;
int step[4][2] = { 0,1,0,-1,1,0,-1,0 };
void bfs()
{
	while (qq.size() != 0)
	{
		ppi t = qq.front();
		qq.pop();
		for (int i = 0; i < 4; i++)
		{
			int x = t.first + step[i][0], y = t.second + step[i][1];
			if (x == zx && y == zy)
			{
				cout << d[t.first][t.second] + 1;
				return;
			}
			if (g[x][y] == '0' && x >= 1 && x <= n && y >= 1 && y <= n&&v[x][y]==0)
			{
				qq.push({ x,y });
				v[x][y] = 1;
				d[x][y] = d[t.first][t.second] + 1;
			}
		}
	}
}
int main()
{
	cin >> n ;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			cin >> g[i][j];
		}
	}
	int a, b;
	cin >> a >> b;
	d[a][b] = 0;
	v[a][b] = 1;
	qq.push({a,b});
	cin >> zx >> zy;
	bfs();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值