Graph Theory

Snakes and Ladders Game Code



Hello people…! In this post, we will discuss about the Snakes and Ladders Game Code, where we find the shortest path to win the Snakes and Ladders game by using the Breadth First Search (BFS) Algorithm. If you don’t know the algorithm, I suggest you read my post on Breadth First Search Algorithm.


This game needs no introduction. We all must have played it in our childhood. I will explain you, how by using Graphs and BFS we can find the Shortest Path to win the game, and, we will state that path and the number of moves of dice it takes too. Have a good look at the Snakes and Ladder board below, we will be using it as an example throughout this post.

Snakes and Ladders
Snakes and Ladders



Dice Roll from Block 1
Dice Roll from Block 1


Dice Roll for Block 1 - 5
Dice Roll for Block 1 – 5




Dice Roll for Block 25
Dice Roll for Block 25


Adjustments to the Adjacency List
Adjustments to the Adjacency List



  • In the beginning of the program, I added all the edges as though the Game Board had no snakes or ladders at all (these number of edges is what I printed), then, I removed the respective edges concerning the snakes and ladders one-by-one.
  • I put all this replacing stuff in a function replace() which takes the Linked List and searches for a value ‘oldVertex’ and replaces it with the value ‘newVertex’ when it finds it.
  • I have added a recursive function, printShortestPath() which recursively looks at the parent of each vertex until the start vertex is reached. It keeps printing vertices as the recursion stack keeps popping out, thus we get the path in a reverse order. Think about this for a while… Trust me… It is easy…! 😉

Link to code – GitHub

If you can solve this problem, then you can solve Snakes and Ladders: The Quickest Way Up problem of HackerRank. You can think of extending this to a 20 ✗ 20 Snakes and Ladder board or an nn board. You just have to add n2 edges to the graph. Solving puzzles by Graph Theory is real fun. I hope this post helped you. If you have any doubts, feel free to comment them. Keep practicing… and… Happy Coding…! 🙂

53 thoughts on “Snakes and Ladders Game Code

  1. import*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;

    public class Solution{
    public static void bfs(int ver,LinkedList adj[],int s)
    boolean visited[] = new boolean[ver+1];
    int count=0;
    int max=0;
    // Create a queue for BFS
    LinkedList queue = new LinkedList();

    // Mark the current node as visited and enqueue it

    while (queue.size() != 0)

    s = queue.poll();


    Iterator i = adj[s].listIterator();
    while (i.hasNext())
    int n =;
    if (!visited[n])
    visited[n] = true;

    public static void main(String args[])
    int t;
    Scanner sc=new Scanner(;
    int ver=100;
    LinkedList adj[];
    adj=new LinkedList[ver+1];
    int snaknum;
    int laddnum;
    int snak[][]=new int[snaknum][2];
    int ladd[][]=new int[laddnum][2];

    for(int i=0;i<=ver;i++)
    adj[i]=new LinkedList();
    for(int i=1;i<=ver;i++)
    for(int j=1;j<=6&&i+j<=100;j++)
    for(int i=0;i<laddnum;i++)
    int j=ladd[i][0]-6;
    for(int i=0;i<snaknum;i++)
    int j=snak[i][0]-6;


    Iterator j = adj[i].listIterator();
    System.out.print( ” “);




    i m getting index out of bound error at line
    and adj[j].set(snak[i][0],snak[i][1]);
    plz help me out with this implementation

  2. Can you please explain Input/Output 2

    Why is the answer not
    1 80 86 92 96 100

    Still 5 moves but wouldn’t that be the logical maximum steps?

  3. Great article and appreciate the effort you put into this. I didn’t read the whole thing yet but right of the bat, I noticed something that immediately throw me off.

    Keep in mind, this is my first time coming in contact with Graph Theory after attempting to do the challenge with just simple functions.

    My question is, in your adjacency lists, why would you throw Dice 1 at the far end and go up in dice number from right to left. This had me really confused. Its much easier to understand

    Vertex 1 -> Dice 1 -> Dice 2 -> Dice 3 -> Dice 4 -> Dice 5 -> Dice 6

    1. The “Dice X” notation labels the edges… It denotes if ‘X’ appears on the dice, where would you go from the current position to the next position… For example… Vertex 1 → Dice 1 → Vertex 2… This means when you get 1 on your dice, you move from Vertex 1 to Vertex 2… So, in my figure where there’s a ladder… Let’s say you are on Vertex 1, by Dice 1 (arrow given below) you go to Vertex 2, then by Dice 4 (arrow on top) you go to Vertex 6, which is being on Vertex 27… So the path would be…. Vertex 1 → Dice 1 → Vertex 2 → Dice 4 → Vertex 6 (→ ladder →) Vertex 27 ….. It is simple… Just give it a little thought! 😉

  4. hey man, I’m unable to understand what’s happening in breadthFirstSearch function, to be more specific its about the parent and level arrays and also in this function you have commented a working portion of the code.

    1. Okay, I understood that parent helps in tracing the path and level gives the shortest path. But what’s the use of if(level[i]==lev) part?

  5. Thanks Vamsi,

    Explanation is really helpful.
    I am not familier with C language could you please write same in java.

  6. There is a mistake here:

    “… We assume that getting caught by a snake is always unfavorable, and will not add to the progress of a short path…”

    That is false. Is easy find an example.

  7. Hello, how would I go about doing an adjacency list in Java 8? I don’t know how to implement from C language…

    1. It is simple BFS… If a vertex has only NULL, it means there are no adjacent vertices… So BFS just skips this vertex… Have a look at the while loop at line 52 🙂

    1. Sorry for the late reply… We have applied BFS on all the vertices… BFS gives us the shortest distances from a vertex to the start vertex, which is nothing but the level of that vertex, and we also get the parent of each vertex, that is, from which vertex have we reached a particular vertex on our shortest path. Now, I am accessing level[100], where the value 100 is stored in vertices… So I get the shortest path to the 100th vertex… To print the path, I recursively keep looking at the parent of the vertices starting from 100th vertex till I’ve reached the start vertex… I hope you get it, give it some time, I’m sure you’ll understand it! 🙂

    1. I haven’t done any projects based on Graph theory yet, but I guess they’ll mostly include visualization related ones…. Like, building a maze, or a racetrack (maybe done by randomized DFS)… Or you could do graph coloring related projects like coloring world map, or the traffic flow problem… Or you could do some visualization of routing algorithms… Looking to do a project to build a maze… I’ll surely make a post here if I do… 🙂

    1. It was meant for a vertex which does not have a parent, in which case the parent value would be zero… It is not needed here as the parent values would come out just fine… I simply used the path printing function in my Bellman Ford algorithm code. The no parent vertex case was a corner case in that scenario… We don’t need it here… If you want to learn more about the other case, I suggest you to go through the comments in my post on Bellman Ford Algorithm.. 🙂

    1. Hi Kushank..! This is the proper algorithm to find the shortest way to win the game…. Can you be more specific as to what exactly you want in your algorithm so that I can help you properly…? 🙂

      1. I made some changes to your code

        Vertices = 9 ;
        so it throws me an error – Segmentation Fault.

        I make further Changes and it Works .

        1)//Dealing with Snakes Edges

        j = v1 – 6;

        if (j < 1) {
        j = 1;
        2) replacing 100 with vertices every where you have 100 except initialization.

Leave a Reply