VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-length-snake-sequence/

⇱ Find maximum length Snake sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find maximum length Snake sequence

Last Updated : 17 Nov, 2022

Given a grid of numbers, find maximum length Snake sequence and print it. If multiple snake sequences exists with the maximum length, print any one of them.

A snake sequence is made up of adjacent numbers in the grid such that for each number, the number on the right or the number below it is +1 or -1 its value. For example, if you are at location (x, y) in the grid, you can either move right i.e. (x, y+1) if that number is ± 1 or move down i.e. (x+1, y) if that number is ± 1.

For example,
9, 6, 5, 2 
8, 7, 6, 5 
7, 3, 1, 6 
1, 1, 1, 7
In above grid, the longest snake sequence is: (9, 8, 7, 6, 5, 6, 7)

Below figure shows all possible paths:

👁 snakesSequence

We strongly recommend you to minimize your browser and try this yourself first.

The idea is to use Dynamic Programming. For each cell of the matrix, we keep maximum length of a snake which ends in current cell. The maximum length snake sequence will have maximum value. The maximum value cell will correspond to tail of the snake. In order to print the snake, we need to backtrack from tail all the way back to snake’s head.

Let T[i][i] represent maximum length of a snake which ends at cell (i, j), 
then for given matrix M, the DP relation is defined as
T[0][0] = 0 
T[i][j] = max(T[i][j], T[i][j - 1] + 1) if M[i][j] = M[i][j - 1] ± 1 
T[i][j] = max(T[i][j], T[i - 1][j] + 1) if M[i][j] = M[i - 1][j] ± 1

Below is the implementation of the idea 


Output
Maximum length of Snake sequence is: 6
Snake sequence is:
9 (0, 0)
8 (1, 0)
7 (1, 1)
6 (1, 2)
5 (1, 3)
6 (2, 3)
7 (3, 3)

Time complexity of above solution is O(M*N). Auxiliary space used by above solution is O(M*N). If we are not required to print the snake, space  can be further reduced to O(N) as we only uses the result from last row.

Comment
Article Tags: