P1135 bfs 58pts 求调
查看原帖
P1135 bfs 58pts 求调
1126838
yyc_0124楼主2024/7/19 13:21

使用bfs 数组 58 pts

#include<bits/stdc++.h>
using namespace std;
int n , a , b;
int k[210][2];// 每个楼层能上去或下去的楼层数 
int edge[210];// bfs 遍历顺序
bool vis[210];// 判断是否到访
int step[210];// 记录每一层答案
int ans;// 记录最终答案
int check (int x) {
	if (x < 1 || x > n){
		return 0;
	}
	else {
		return 1;
	}
} // 检查是否越界
void bfs(int a , int b) {
	int now = a;// 目前层数
	int head = 0 , tail = 1;
	int sum = 0;// 目前步数
	vis[a] = 1;// 目前已到访
	step[a] = 0;
	edge[1] = a;
	ans = -1;
	while (head < tail){// 还有没遍历的点
		head++;// 到下一个遍历点
		sum = step[head] + 1;// 增加步数
		for (int i = 0 ; i <= 1 ; i++){
			now = edge[head] + k[edge[head]][i];
			if (check(now) == 1 && vis[now] == 0){
				tail++;
				vis[now] = 1;
				edge[tail] = now;
				step[tail] = sum;
				if (now == b){
					ans = sum;
				}
			}
		}	
	}
} // bfs
int main(){
	cin >> n >> a >> b;
	int tmp;
	for (int i = 1 ; i <= n ; i++){
		cin >> tmp;
		k[i][1] = tmp;
		k[i][0] = -tmp;
	}
	memset (step , -1 , sizeof(step));
	bfs(a , b);
	cout << ans;
	return 0;
}

//はいばらあい
2024/7/19 13:21
加载中...