Snake and Ladder Problem
Given a snake and ladder board, find the minimum number of dice throws required to reach the destination. And suppose you have control over outcome of dice throw.
If you gets ladder you will climb up, but in case of snake you will be moved down.
Algorithm
- Create a visited boolean array to hold visited vertices info
- Create an Class name Entry to hold following attributes’ value:
- vertex
- moves
- Create a queue which will hold above above
- Create an object of Entry with value vertex=0 and moves=0
- Iterate till queue is not empty
- entry = queue.dequeue
- If
entry.vertex == goalVertex
thenreturn entry.moves
- Iterate from entry.vertex +1 to entry.vertex+ 6
- if vertex is not visited then
- Create and new entry with vertex=vertex and moves=entry.moves+1
queue.enqueue(entry)
Latest Source Code:
Github: SnakeLadder.java
Output:
Number move required : 3