Simple BFS Java Solution


#1
public class Solution {
    public int snakeLadder(ArrayList<ArrayList<Integer>> A, ArrayList<ArrayList<Integer>> B) {
        
        HashMap<Integer,Integer> ladder=new HashMap<>();
        HashMap<Integer,Integer> snake=new HashMap<>();
        
        for(ArrayList<Integer> l : A)
        {
            ladder.put(l.get(0),l.get(1));
        }
        for(ArrayList<Integer> s : B)
        {
            snake.put(s.get(0),s.get(1));
        }
        
        return bfs(ladder,snake);
    }
    
    public int bfs(HashMap<Integer,Integer> ladder,HashMap<Integer,Integer> snake)
    {
        int distances[]=new int[101];
        boolean visited[]=new boolean[101];
        
        Queue<Integer> q=new ArrayDeque<>();
        q.add(1);
        
        while(!q.isEmpty())
        {
            int currPosition=q.poll();
            visited[currPosition]=true;
            
            for(int i=1;i<=6;i++)
            {
                int newPosition=i+currPosition;
                
                if(ladder.containsKey(newPosition))
                    newPosition=ladder.get(newPosition);
                if(snake.containsKey(newPosition))
                    newPosition=snake.get(newPosition);
                
                
                if(newPosition<=100 && !visited[newPosition])
                {
                    visited[newPosition]=true;
                    distances[newPosition]=distances[currPosition]+1;
                    q.add(newPosition);
                    
                    if(newPosition==100)
                       return distances[newPosition];
                }
            }
        }
        return -1;
    }
}