Snake and Ladder Problem | Practice | GeeksforGeeks

Given a 5x6 snakes and ladders board, find the minimum number of dice throws required to reach the destination or last cell (30th cell) from the source (1st cell). 
You are given an integer N denoting the total number of snakes and ladders and an array arr[] of 2*N size where 2*i and (2*i + 1)th values denote the starting and ending point respectively of ith snake or ladder. The board looks like the following.

                                   
Example 1:
Input:
N = 8
arr[] = {3, 22, 5, 8, 11, 26, 20, 29, 
       17, 4, 19, 7, 27, 1, 21, 9}
Output: 3
Explanation:
The given board is the board shown
in the figure. For the above board 
output will be 3. 
a) For 1st throw get a 2. 
b) For 2nd throw get a 6.
c) For 3rd throw get a 2.

Your Task:
You do not need to read input or print anything. Your task is to complete the function minThrow() which takes N and arr as input parameters and returns the minimum number of throws required to reach the end of the game.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ N ≤ 10
1 ≤ arr[i] ≤ 30  
+3
spideyy4 days ago
BFS by default returns shortest path
int minThrow(int N, int arr[]){
       unordered_map<int,int> ladders;
       unordered_map<int,int> snakes;
       int n = N*2;
       for(int i=1;i<n;i+=2){
           if(arr[i-1]<arr[i]) ladders[arr[i-1]] = arr[i];
           else if(arr[i-1]>arr[i]) snakes[arr[i-1]] = arr[i];
       }
       //from 1 to 6 kuch bhi aa skta hai phele
       queue<pair<int,int>>q; //position, no. of moves
       q.push({1,0});
       while(!q.empty()){
           int node = q.front().first;
           int moves = q.front().second;
           q.pop();
           if(node==30) return moves;
           for(int i=1;i<=6;i++){
               int x = i+node;
               if(ladders.find(x)!=ladders.end()){
                   q.push({ladders[x],moves+1});
               }else if(snakes.find(x)!=snakes.end()){
                   q.push({snakes[x],moves+1});
               }else{
                   q.push({x,moves+1});
               }
           }
       }
       return -1;
   }
0
saadhvikmvk94 days ago
can i get c code
+2
mahendrareddy2345671 week ago
class Solution{public:   int minThrow(int N, int arr[]){       // code here       unordered_map<int,int>snk;       unordered_map<int,int>lad;       for(int i=0;(i+1)<N*2;i+=2)       {           if(arr[i]<arr[i+1])               lad[arr[i]]=arr[i+1];           else               snk[arr[i]]=arr[i+1];       }       int moves=0;       queue<int>q;       q.push(1);       vector<int>vis(31,0);       vis[1]=1;       bool flag=false;       while(!q.empty() && flag==false)       {           int n=q.size();           while(n--)           {               int t=q.front();               q.pop();               for(int i=1;i<=6;i++)               {                   if(t+i==30)                   {                       flag=true;                   }                   else if(t+i<=30 and lad[t+i] and !vis[lad[t+i]])                   {                       vis[lad[t+i]]=1;                       if(lad[t+i]==30)                       {                           flag=true;                       }                       q.push(lad[t+i]);                   }                   else if(t+i<=30 and snk[t+i] and !vis[snk[t+i]])                   {                       vis[snk[t+i]]=1;                       if(snk[t+i]==30)                       {                           flag=true;                       }                       q.push(snk[t+i]);                   }                   else if(t+i<=30 and !vis[t+i])                   {                       vis[t+i]=1;                       q.push(t+i);                   }               }           }           moves++;       }       if(flag==false)       {           return -1;       }       return moves;   }};
+2
mahendrareddy234567
This comment was deleted.
0
moaslam8262 weeks ago
c++ BFS soln
int dfs(int vertex,vector<int> arr[],vector<bool> &isvisted,int N){
  int ans=0;
  queue<int> q;
  q.push(vertex);
  q.push(-1);
  while(1){
      int i=q.front();
      q.pop();
      if(i==30) break;
      if(i==-1){
          ans++;
          q.push(-1);
      }else{
       for(int j=0;j<arr[i].size();j++){
              if(!isvisted[arr[i][j]]){                     isvisted[arr[i[j]]=true;
                  q.push(arr[i][j]);
              }
          }
      }
  }
  return ans;   
}
    int minThrow(int n, int arr[]){
       int N=31;
       vector<int> graph[N];
       vector<bool> isvisted(N,false);
       unordered_map<int,int> um;
       // //putting snake and ladder
      for(int i=0;i<2*n;i++){
         um[arr[i]]=arr[i+1];
          i++;
      }
       //making graph
           for(int i=1;i<=N-1;i++){
  	        for(int j=1;j<=6;j++){
             if(i+j<=N-1){
                 if(um.count(i+j)==0)
                  graph[i].push_back(i+j);
                  else                 graph[i].push_back(um[i+j]);
             }
     	}
       }
       //making dfs
       isvisted[1]=true;
       return dfs(1,graph,isvisted,N);
       //thanks gfg
    }
0
19bcs13142 weeks ago
Java Solution using BFS 
 
 
class Solution{
    static int minThrow(int n, int arr[]){
        // code here
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<2*n;i+=2){
            map.put(arr[i],arr[i+1]);
        }
        boolean[] visit=new boolean[31];
        
        visit[1]=true;
        
        Queue<Integer> q=new LinkedList<>();
        q.add(1);
        int count=0;
        
        while(q.size()!=0){
            
            int siz=q.size();
            
            for(int i=0;i<siz;i++){
                int curr=q.remove();
                if(curr==30){
                        return count;
                }
                for(int j=1;j<=6;j++){
                    int temp=curr+j;
                    
                    if(temp>30){
                        break;
                    }
                    
                    if(map.containsKey(temp) && visit[map.get(temp)]==false){
                        visit[temp]=true;
                        q.offer(map.get(temp));
                        visit[map.get(temp)]=true;
                    }
                    else if(visit[temp]==false){
                        q.offer(temp);
                        visit[temp]=true;
                    }
                    
                }
                
                
            }
            count++;
        }
        
        return -1;
    }
}
0
neeshumaini552 weeks ago
#0.2 sec to run all the test case
#one of the most efficient algorithms to solve this problem
#BFS 
from collections import deque
class Solution:
    def minThrow(self, N, arr):
        #creating the board
        board = [-1]*31   
        for i in range(0,2*N,2):
            board[arr[i]] = arr[i+1]
        #print(board)
        
        queue = deque()
        queue.append([1,0])#square,moves
        visited = set()
        while queue:
            #moves += 1
            a,b = queue.popleft()
            for i in range(1,7):
                next_ = a + i
                #print(next_)
               
          		#check if there is a snake or ladder at that postion
                if board[next_] != -1:
                    next_ = board[next_]
                    #print(next_)

                #if the boaRd is equal to 30 return moves
                if next_ == 30:
                    return b + 1
                if next_ not in visited:
                    visited.add(next_)
                    queue.append([next_,b + 1])
        return -1
        
0
sanketbhagat3 weeks ago
SIMPLE JAVA SOLUTION
class Solution{
    static int minThrow(int n, int arr[]){
        // code here
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<2*n;i+=2) map.put(arr[i],arr[i+1]);
        boolean visited[] = new boolean[31];
        Queue<Integer> q = new LinkedList<>();
        q.offer(1);
        visited[1] = true;
        int count = 0;
        while(!q.isEmpty()){
            int len = q.size();
            for(int i=0;i<len;i++){
                int curr = q.poll();
                if(curr==30) return count;
                for(int j=1;j<=6;j++){
                    if(curr+j>30) break;
                    if(map.containsKey(curr+j) && !visited[map.get(curr+j)]){
                        visited[map.get(curr+j)] = true;
                        q.offer(map.get(curr+j));
                    }else if(!visited[curr+j]){
                        visited[curr+j] = true;
                        q.offer(curr+j);
                    }
                }
            }
            count++;
        }
        return -1;
    }
}
0
debug041 month ago
int minThrow(int N, int arr[]){
        // code here
        int moves=0;
        vector<int> vis(30, 0);
        vector<int> brd(30, -1);
        
        for(int i=0; i<2*N; i=i+2)
            brd[arr[i]]=arr[i+1];
        
        
        queue<int> stk;
        stk.push(1);
        vis[1]=1;
        
        while(!stk.empty()){
            int currStkSize = stk.size();
            moves++;
            for(int i=0; i<currStkSize; i++){
                int node=stk.front();
                stk.pop();
                for(int j=1; j<=6; j++){
                    int nxtNode=node+j;
                    if(nxtNode==30) return moves;
                    else if(nxtNode>30) continue;
                    else if(nxtNode<30 and !vis[nxtNode] and brd[nxtNode]!=-1){
                        if(brd[nxtNode]==30){
                            return moves;
                        }
                        vis[nxtNode]=1;
                        stk.push(brd[nxtNode]);
                    }
                    else {
                        vis[nxtNode]=1;
                        stk.push(nxtNode);
                    }
                }
            }
        }
        
        return -1;
    }
0
bhaskarmaheshwari81 month ago
int minThrow(int N, int arr[]){       // code here       //refer  https://www.youtube.com/watch?v=2ulHQOGYmxI&t=420s       queue<pair<int,int>> q;       vector<int> vis(31,0);       vector<int>moves(31,-1);       for(int i=0;i<2*N;i=i+2)//2*N imp yaha pe       {           moves[arr[i]]=arr[i+1];       }       q.push({1,0});       vis[1]=1;       while(!q.empty())       {           pair<int,int> p=q.front();           q.pop();           int cell=p.first;           int turn=p.second;           if(cell==30)           return p.second;           for(int i=cell+1;i<=cell+6&&i<=30;i++)           {               pair<int,int> pp;               if(!vis[i])               {                   vis[i]=1;                   if(moves[i]!=-1)                   pp.first=moves[i];                   else                   pp.first=i;                                      pp.second=turn+1;                   q.push(pp);               }           }       }          }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.