求助!求助,只能AC五个点,实在找不到哪里错了....
查看原帖
求助!求助,只能AC五个点,实在找不到哪里错了....
150750
sakura、楼主2022/4/1 00:24

我是用bfs写的,代码如下 判断上下楼我是创建了一个数组,里面是1和-1,每次乘于就能达到上下楼的目的

import java.util.*;
public class stair {
	static int n,a,b;//楼层数,起始楼层,目标楼层
	static int[] updown = {1, -1};//判断上楼还是下楼
	static int[] k = new int[200];	//存放每个楼层的值
	static boolean[] vis = new boolean[200];//标记楼层是否访问过
	static class node {
		int floor;
		int step;
		node(int floor, int step) {
			this.floor = floor;//楼层
			this.step = step;//按钮次数
		}
	}//创建一个node类,辅助遍历
	static node num;//存放结果
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		a = sc.nextInt();
		b = sc.nextInt();
		for (int i = 1; i <= n; i++) {
			k[i] = sc.nextInt();
			vis[i] = true;
		}//vis初始化全为true,因为一开始全部楼层都是可以访问的
		bfs();
	}
	
	static void bfs() {
		Deque<node> de = new ArrayDeque<>();
		de.push(new node(a,0));//推入a,0 代表起始楼层以及按钮次数
		while (!de.isEmpty()) {
			num = de.poll();
			if (num.floor == b) {
				break;
			}//当前楼层floor==b,退出循环
			for (int i = 0; i < 2; i++) {
				int next = num.floor + k[num.floor] * updown[i];
				//分别*1和-1,代表上下楼
				if (next > 0 && next <= n && vis[next]) {
					vis[next] = false;
					de.push(new node(next, num.step + 1));
				}
			}
		}
		if (num.floor == b) {
			System.out.println(num.step);
		}
		else {
			System.out.println(-1);
		}
	}
}
2022/4/1 00:24
加载中...