Find longest Snake sequence in a given matrix

Objective: Given a two-dimensional matrix, write an algorithm to find out the snake sequence which has the maximum length. There could be many snake sequences in the matrix, you need to return the one with the maximum length. Travel is allowed only in two directions, either go right OR go down.

What is snake sequence: A snake sequence can be made if the number in the adjacent right cell or the number in the adjacent down cell is either +1 or -1 from the number in the current cell.


Snake Sequence (1)


  • This problem is the extension of the problem “Count all paths from top left to bottom right of a mXn matrix” with some extra conditions.
  • You can travel only in two directions, either go right or go down.
  • All we need to take care of is one extra condition that we can travel only to the adjacent cells (right or down) only if the number in those cells has a difference of 1 from the current cell.
  • Have a temporary storage, two-dimensional array to store the results of the snake result.
  • Keep tracking of maximum length and at the end print the sequence using a temporary array.
  • We will use the Bottom-up approach of Dynamic pro­gram­ming and store the results of sub prob­lems to reuse them in the future.
  • See the recursive equation and code for a better understanding.
Recursive Equation- Snake Sequence



Max Snake Sequence : 7
- 5 - 4 - 3 - 2 - 1 - 2 - 1

5 thoughts on “Find longest Snake sequence in a given matrix”

  1. if I change the order of “if else” statements in print path function the printed sequence doesn’t match with the expected sequence.

    Should we always start checking the row first and then column?

  2. Below function should also do that please let me know if you see any issues

    To call

    Stack longest = new Stack();
    findMaxLengthSnake(A,0,0,new Stack(),longest);

    and the function

    private static Stack findMaxLengthSnake(int[][] matrix,int row, int column, Stack currentPath,Stack longest) {
    if(currentPath.size() > longest.size()){
    if(row==matrix.length || matrix[row].length == column){
    return currentPath;
    int currentValue = matrix[row][column];
    if(!currentPath.isEmpty() && Math.abs(currentPath.peek()-currentValue) != 1){
    return currentPath;
    findMaxLengthSnake(matrix, row, column+1,currentPath,longest);
    findMaxLengthSnake(matrix, row+1, column,currentPath,longest);
    return currentPath;

  3. This algorithm is not entirely right, it is missing the condition of checking for meeting the condition in the original matrix before print. If you run it for the following example you will see that it fails.
    int arrA [][] = {{1, 2, 3, 9},
    {2, 9, 2, 1},
    {3, 9, 9, 2},
    {4, 5, 6, 7}};

    Max Snake Sequence : 7
    – 7 – 2 – 1 – 2 – 3 – 2 – 1


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.