Continuing the discussion from TRAVELLING - Editorial:
import java.util.*;
import java.lang.*;
import java.util.*;
public class Main
{
static class Pair{
int a;int b;
public Pair(int a,int b){
this.a=a;
this.b=b;
}
}
static class SortA implements Comparator<Pair>{
public int compare(Pair s1,Pair s2){
if(s1.b<s2.b){
return -1;
}else if(s1.b>s2.b){
return 1;
}
return 0;
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int citizens = sc.nextInt();
for(int z=0;z<citizens;z++){
int n=sc.nextInt();
int m=sc.nextInt();
List<List<Pair>>l=new ArrayList<>();
for(int i=0;i<n+2;i++){
l.add(new ArrayList<>());
}
for(int i=1;i<=n;i++){
l.get(i).add(new Pair(i+1,1));
l.get(i+1).add(new Pair(i,1));
}
for(int i=0;i<m;i++){
int a=sc.nextInt();
int b=sc.nextInt();
l.get(a).add(new Pair(b,0));
l.get(b).add(new Pair(a,0));
}
int dis[]=new int[n+2];
PriorityQueue<Pair>q=new PriorityQueue<>(new SortA());
q.add(new Pair(1,0));
Arrays.fill(dis,Integer.MAX_VALUE);
dis[1]=0;
while(q.size()>0){
Pair t=q.poll();
if(t.a==n){
System.out.println(dis[n]);
break;
}
List<Pair>l1=l.get(t.a);
for(int i=0;i<l1.size();i++){
if(dis[l1.get(i).a]>t.b+l1.get(i).b){
dis[l1.get(i).a]=t.b+l1.get(i).b;
q.add(new Pair(l1.get(i).a,dis[l1.get(i).a]));
}
}}
//System.out.println(dis[n]);
}
}}
Why is my code giving tle