Find the longest path in a matrix where each step has entries that differ by 1
So a couple of remarks:


If I understand the required solution, you seem to have a bug, e.g. longestWorm(new int[][]{{0, 1, 3}, {9, 8 ,7}, {4, 5, 6}}) returns 10, although there are only 9 numbers. The wormcount calculation is then wrong because you increment the counter twice instead of once. Recursively defining the problem, you can say that the length of a path is the length of the current cell (which is one), summed by the length of the remaining path. Which would make the length function something like:

private static int wormCount(int[][] mat, int i, int j){
    if (i &lt; mat.length - 1 &amp;&amp; mat[i][j] == mat[i + 1][j] + 1) {
        return 1 + wormCount(mat, i + 1, j);
    }
    ....
    return 1;
}



This also makes the base case very clear. You also do not necessarily need to pass the count variable. Only perhaps if you would want to make it a tail-recursive function, but AFAIK in Java it will not help you eliminate a stack overflow.


The problem is defined as finding a path of increasing order, but your code seems to calculate it the other way around. Not wrong, but slightly confusing.
In the longestWorm function, you calculate the same function twice. This is not necessary:

max = Math.max(max, wormCount(mat, i, j, 0));



You could save it in a local variable if it helps the readeability.

I do not know the optimal way to solve this problem. My guess would be you could at each index calculate the path length, and save it in a table. Because each value is unique, it could simply be a map between the value and the length of the path starting at that value (else, it could simply be a key generated using the indices i and j). Before calculating the length for a particular value (or starting at a particular index), you first look if you already calculated it, which you could then reuse.