Given a snake and ladder board, find the minimum number of dice throws required to reach the destination or last cell from source or 1st cell. Basically, the player has total control over outcome of dice throw and wants to find out minimum number of throws required to reach last cell.
If the player reaches a cell which is base of a ladder, the player has to climb up that ladder and if reaches a cell is mouth of the snake, has to go down to the tail of snake without a dice throw.
For example, consider the board shown, the minimum number of dice throws required to reach cell 30 from cell 1 is 3.
Following are the steps:
a) First throw two on dice to reach cell number 3 and then ladder to reach 22
b) Then throw 6 to reach 28.
c) Finally through 2 to reach 30.
There can be other solutions as well like (2, 2, 6), (2, 4, 4), (2, 3, 5).. etc.
The idea is to consider the given snake and ladder board as a directed graph with number of vertices equal to the number of cells in the board. The problem reduces to finding the shortest path in a graph. Every vertex of the graph has an edge to next six vertices if next 6 vertices do not have a snake or ladder. If any of the next six vertices has a snake or ladder, then the edge from current vertex goes to the top of the ladder or tail of the snake. Since all edges are of equal weight, we can efficiently find shortest path using Breadth First Search of the graph.
Following is the implementation of the above idea. The input is represented by two things, first is ‘N’ which is number of cells in the given board, second is an array ‘move[0…N-1]’ of size N. An entry move[i] is -1 if there is no snake and no ladder from i, otherwise move[i] contains index of destination cell for the snake or the ladder at i.
Min Dice throws required is 3
Time complexity of the above solution is O(N) as every cell is added and removed only once from queue. And a typical enqueue or dequeue operation takes O(1) time.
This article is contributed by Siddharth. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Word Ladder (Length of shortest chain to reach a target word)
- Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap)
- Nuts & Bolts Problem (Lock & Key problem) | Set 1
- Water Jug problem using BFS
- Tiling Problem
- Subset Sum Problem | DP-25
- Box Stacking Problem | DP-22
- Partition problem | DP-18
- The Celebrity Problem
- 2-Satisfiability (2-SAT) Problem
- Subset Sum Problem in O(sum) space
- Water Connection Problem
- A Peterson Graph Problem
- Level Ancestor Problem
- Channel Assignment Problem