牛客练习赛24.E-青蛙(最短路)

题目描述 
有一只可爱的老青蛙,在路的另一端发现了一个黑的东西,想过去一探究竟。于是便开始踏上了旅途

一直这个小路上有很多的隧道,从隧道的a进入,会从b出来,但是隧道不可以反向走。

这只青蛙因为太老了,所以很懒,现在想请你帮帮慢,问他最少需要几步才可以到达对面。

将小径看作一条数轴,青蛙初始在0上,这只青蛙可以向前跳也可以向后跳,但每次只能跳一格,每跳一格记作一步,从隧道进到隧道出算做一步。

输入描述:
第一行两个数m,n;表示黑色物品在数轴m点上,数轴上总共有n个隧道
接下来n行,每行a,b两个数,表示从a进会从b出

10 <= m,n <= 233

0<a,b<=m
输出描述:
一个数ans表示最小步数
示例1

输入
复制

16 4
2 10
8 15
12 5
13 6
输出
复制

7
说明
 
0-->1-->2-->10-->9-->8-->15-->16

思路:这题我是在学动态规划里看到的,看了半天也不知道动态规划怎么下手,越看越像bfs,所以还是用bfs写了,不过也借鉴了其他大佬的写法(纯小白),用bfs还是挺方便的,也可以用这个题练一练bfs,上代码。

 

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<map>
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h> 
#include<string.h>
#include<stack>
#include<queue>
#include<list>
#include<numeric>
#include<set>
#include<cstring>
#include<bitset>
#include<string>
#include<deque>
#include<vector>
#define ll long long
const ll inf = 0x3f3f3f3f3f3f3f3f;//表示无穷大
using namespace std;
//a&1==a%2==1(表示是奇数)
ll gcd(int a, int b)
{
	return (!b ? a : gcd(b, a % b));
}
const int ma = 1e5 + 10;
int fx[2] = { -1,1 };//方向数组,向前或向后
int n, m,ans=0,vv[2500];//记录该点有没有被访问
struct node {
	int x;//坐标
	int t;//步数
};
vector<int>v[3000];//隧道数组
bool check(int y)//判断是否出界
{
	if (y >= 0 && y <= 1000)
		return 1;
	return 0;
}
void bfs()
{
	queue<node>q;
	node tm, now;
	tm.x = 0;
	tm.t = 0;
	q.push(tm);
	vv[0] = 1;
	while (!q.empty())
	{
		tm = q.front();
		q.pop();
		if (tm.x == m)
		{
			ans = tm.t;
			return;
		}
		for (int i = 0; i < 2; i++)//向前或向后搜索
		{
			now.x = tm.x + fx[i];
			now.t = tm.t + 1;
			if (check(now.x) && vv[now.x] == 0)
			{
				q.push(now);
				vv[now.x] = 1;
			}
		}
		for (int j = 0; j < v[tm.x].size(); j++)//隧道搜索
		{
			now.x = v[tm.x][j];
			now.t = tm.t + 1;
			if (check(now.x) && vv[now.x] == 0)
			{
				q.push(now);
				vv[now.x] = 1;
			}
		}
	}
}
int main()
{
	int a, b, i;
	cin >> m >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> a >> b;
		v[a].push_back(b);
	}
	memset(vv, 0, sizeof(vv));
	bfs();
	cout << ans << endl;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值