Java BFS Solution


#1
public class Solution {
HashMap<Integer,Integer> ladder=new HashMap<Integer,Integer>();
HashMap<Integer,Integer> snake=new HashMap<Integer,Integer>();
int bfs()
{
    int[] dp=new int[101];
    boolean[] visited=new boolean[101];
    visited[1]=true;
    Queue<Integer> q=new LinkedList<>();
    q.add(1);
    while(q.isEmpty()==false)
    {
        int curr=q.poll();
        for(int i=1;i<=6;i++)
        {
            int child=curr+i;
            if(ladder.containsKey(child))
            child=ladder.get(child);
            if(snake.containsKey(child))
            child=snake.get(child);
            if(child<=100 && visited[child]==false)
            {
                dp[child]=dp[curr]+1;
                visited[child]=true;
                q.add(child);
            }
        }
    }
    if(dp[100]==0)
    return -1;
    return dp[100];
}
public int snakeLadder(int[][] A, int[][] B) {
    for(int i=0;i<A.length;i++)
    ladder.put(A[i][0],A[i][1]);
    for(int i=0;i<B.length;i++)
    snake.put(B[i][0],B[i][1]);
    int res=bfs();
    return res;
    
}

}