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.
- Puzzle | (Square and Right angles, Up the Ladder)
- Snake case of a given sentence
- Design Snake Game
- Print matrix in snake pattern
- Find maximum length Snake sequence
- Is the future with snake(Python) or Coffee(Java) ?
- Word Ladder (Length of shortest chain to reach a target word)
- Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
- Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap)
- Secretary Problem (A Optimal Stopping Problem)
- Nuts & Bolts Problem (Lock & Key problem) | Set 1
- C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)
- How to get rid of Java TLE problem
- Water Jug problem using BFS
- 2-Satisfiability (2-SAT) Problem