Java P1135 奇怪的电梯

题目链接
bfs题目,不多说
下面是AC代码

import java.util.*;
import java.math.*;
public class Main {
     
    
    public static void main(String[] args){
     
    	Scanner sc=new Scanner(System.in);
    	int n=sc.nextInt();
    	int a=sc.nextInt();
    	int b=sc.nextInt();
    	int[] k=new int[n+1];
    	for(int i=1;i<=n;i++)
    		k[i]=sc.nextInt();
    	System.out.println(bfs(k,a,b));
    }
    public static int bfs(int[] k,int a,int b){
     
    	if(a==b)
    		return 0;
    	int n=k.length-1;
    	Queue<Integer> q=new LinkedList<Integer>();
    	q.offer(a);
    	int step=0;
    	boolean[] isz=new boolean[n+1];
    	while(!q.isEmpty()){
     
    		int size=q.size();
    		for(int i=0;i<size;i++){
     
    			int cur=q.poll();
    			isz[cur]=true;
    			if(cur+k[cur]==b||cur-k[cur]==b)
    				return step+1;
    			if(cur+k[cur]<=n&&!isz[cur+k[cur]])
    				q.offer(cur+k[cur]);
    			if(cur-k[cur]>0&&!isz[cur-k[cur]])
    				q.offer(cur-k[cur]);
    		}
    		step++;
    	}
    	return -1;
    }
}

你可能感兴趣的:(洛谷,java,bfs,java,算法)