Given a square matrix, print the maximum length snake sequence in it. A snake sequence is defined as a sequence of numbers where each new number, which can only be located to the right or down of the current number, is either plus or minus one.

For example, we can either move right from any cell in the matrix (if that number is ±1) or move down (if that number is ±1). The problem is finding the longest path (snake sequence) through the matrix, keeping in mind that we can only move to a new cell whose value is ±1 concerning the current cell.

 
For example, the maximum length snake sequence of the following matrix is 5 — 4 — 5 — 6 — 7 — 8 — 7 — 6 as highlighted below:

Maximum Length Snake Sequence

Please note that multiple maximum length snake sequences can exist in the matrix. For example, 3 — 4 — 5 — 6 — 7 — 8 — 7 — 6 is another maximum length snake sequence in the above matrix.
 

Practice this problem

 
We can use dynamic programming to solve this problem. For each matrix cell (i, j), we need to calculate the maximum length of a snake, say L[i][j], which ends in that cell. The recurrence relation for calculating L[i][j] will be:

if (abs(M[i][j] – M[i][j – 1]) == 1)
    L[i][j] = max(L[i][j], L[i][j – 1] + 1)
 
if (abs(M[i][j] – M[i – 1][j]) == 1)
    L[i][j] = max(L[i][j], L[i – 1][j] + 1)

Now, the cell with the maximum value will correspond to the snake’s tail, and we can easily trace the path back to the snake’s head using the L[][] matrix. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum length snake sequence is 5 — 4 — 5 — 6 — 7 — 8 — 7 — 6
The length is 7

Java


Download  Run Code

Output:

The maximum length snake sequence is 5 — 4 — 5 — 6 — 7 — 8 — 7 — 6
The length is 7

Python


Download  Run Code

Output:

The maximum length snake sequence 5 — 4 — 5 — 6 — 7 — 8 — 7 — 6
The length is 7

The time complexity of the proposed solution is O(N2) for an N × N matrix. The auxiliary space required by the program is O(N2).

 
Exercise: Extend the solution for a rectangular matrix