Since all numbers are unique and in range from 1 to n * n , there is atmost one possible direction from any cell
if ( j < n - 1 && ( ( mat [ i ] [ j ] + 1 ) == mat [ i ] [ j + 1 ] ) ) { x = dp [ i ] [ j ] = 1 + findLongestFromACell ( i , j + 1 , mat , dp ) ; } if ( j > 0 && ( mat [ i ] [ j ] + 1 == mat [ i ] [ j - 1 ] ) ) { y = dp [ i ] [ j ] = 1 + findLongestFromACell ( i , j - 1 , mat , dp ) ; } if ( i > 0 && ( mat [ i ] [ j ] + 1 == mat [ i - 1 ] [ j ] ) ) { z = dp [ i ] [ j ] = 1 + findLongestFromACell ( i - 1 , j , mat , dp ) ; } if ( i < n - 1 && ( mat [ i ] [ j ] + 1 == mat [ i + 1 ] [ j ] ) ) { w = dp [ i ] [ j ] = 1 + findLongestFromACell ( i + 1 , j , mat , dp ) ; }