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 and ( ( mat [ i ] [ j ] + 1 ) == mat [ i ] [ j + 1 ] ) ) : NEW_LINE INDENT x = 1 + findLongestFromACell ( i , j + 1 , mat , dp ) NEW_LINE DEDENT if ( j > 0 and ( mat [ i ] [ j ] + 1 == mat [ i ] [ j - 1 ] ) ) : NEW_LINE INDENT y = 1 + findLongestFromACell ( i , j - 1 , mat , dp ) NEW_LINE DEDENT if ( i > 0 and ( mat [ i ] [ j ] + 1 == mat [ i - 1 ] [ j ] ) ) : NEW_LINE INDENT z = 1 + findLongestFromACell ( i - 1 , j , mat , dp ) NEW_LINE DEDENT if ( i < n - 1 and ( mat [ i ] [ j ] + 1 == mat [ i + 1 ] [ j ] ) ) : NEW_LINE INDENT w = 1 + findLongestFromACell ( i + 1 , j , mat , dp ) NEW_LINE DEDENT