# 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 at-least 7 dice throws to win.

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.

## Java

Output:

7

(3 votes, average: 5.00 out of 5)

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 🙂

Subscribe
Notify of
Guest
Tarun Mitra

This is awesome, thanks!

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 🙂

Guest
awesome_me

The starting node should be 0,0 instead of 1,0 as you can also land on 1 in first throw and using the ladder get to 38