Luogu P1135 奇怪的电梯

9 篇文章 0 订阅
4 篇文章 0 订阅

原题传送门

DFS版

#include <bits/stdc++.h>
using namespace std;

int N;
int num[205];
bool vis[205];
int beg, end;
int minn = 0x7f7f7f7f;

void dfs(int now, int step)
{
	if (now == end)
	{
		minn = min(minn, step);
		return;
	}

	if (step > minn)
	{
		return;
	}

	vis[now] = true;

	if (now + num[now] <= N && vis[now + num[now]] == false)
	{
		dfs(now + num[now], step + 1);
	}

	if (now - num[now] >= 1 && vis[now - num[now]] == false)
	{
		dfs(now - num[now], step + 1);
	}

	vis[now] = false;
}

int main()
{
	cin >> N >> beg >> end;
	for (int i = 1; i <= N; i++)
	{
		cin >> num[i];
	}
	dfs(beg, 0);
	if (minn == 0x7f7f7f7f)
	{
		cout << -1 << endl;
	}
	else
	{
		cout << minn << endl;
	}
}

BFS版

#include <bits/stdc++.h>
using namespace std;

int N;
int num[205];
bool vis[205];
int beg, end;

queue< pair<int, int> > q;
//pair <floor,step>

void bfs(int start)
{
	q.push(make_pair(start, 0));
	while (!q.empty())
	{
		pair<int, int> fir = q.front();
		q.pop();

		int lastFloor = fir.first;
		if (lastFloor == end)
		{
			cout << fir.second << endl;
			exit(0);
		}

		vis[lastFloor] = true;
		if (lastFloor + num[lastFloor] <= N && vis[lastFloor + num[lastFloor]] == false)
		{
			q.push(make_pair(lastFloor + num[lastFloor], fir.second + 1));
		}
		if (lastFloor - num[lastFloor] >= 1 && vis[lastFloor - num[lastFloor]] == false)
		{
			q.push(make_pair(lastFloor - num[lastFloor], fir.second + 1));
		}
	}
	cout << -1 << endl;
}
int main()
{
	cin >> N >> beg >> end;
	for (int i = 1; i <= N; i++)
	{
		cin >> num[i];
	}

	bfs(beg);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值