Minimum number of throws required to win Snake and Ladder game

Find minimum number of throws required to win given Snake and Ladder game.


 

For example, below game requires atleast 7 dice throws to win.

Snake and Ladder Problem

 

 

The idea is to consider the snack and ladder board as directed graph and run BFS from starting node which is vertex 0 as per game rules. We construct a directed graph keeping in mind below conditions –

1. For any vertex in the graph v, we have an edge from v to v + 1, v + 2, v + 3, v + 4, v + 5, v + 6 as we can reach any of these nodes in one throw of dice from node v.

2. If any of these neighbors of v has a ladder or snake which takes you to position x, then x becomes the neighbor instead of the base of the ladder or head of the snake.

Now the problem is transformed into a Shortest path between two nodes in a directed graph problem. We represent the snake and ladder board using a map.

C++

Download   Run Code

Java

Download   Run Code

Output:

7

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Karan
Guest

If you’re using the int for BFS definition, it should either return node.minDist or if you’re printing as in this case, it should just be void. Something super minor but I figured it’s best if the code is updated.

Thanks for all these wonderful questions 🙂

Tarun Mitra
Guest

This is awesome, thanks!