Domanda di colloquio di Addepar

longest sequence in 2d array

Risposta di colloquio

Anonimo

9 feb 2017

function longestPath(matrix, row, col, prev) { if (row = matrix.length || col = matrix[ 0 ].length || matrix[ row ][ col ] <= prev) { return 0; } var lgth = 0, curr = matrix[ row ][ col ]; lgth = Math.max(longestPath(matrix, row, col + 1, curr), lgth); lgth = Math.max(longestPath(matrix, row + 1, col, curr), lgth); lgth = Math.max(longestPath(matrix, row, col - 1, curr), lgth); lgth = Math.max(longestPath(matrix, row - 1, col, curr), lgth); return lgth + 1; } function longestIncreasingPath(matrix) { var longest = 0; matrix.forEach(function(row, i) { row.forEach(function(col, j) { var lgth = longestPath(matrix, i, j, 0); longest = Math.max(lgth, longest); }); }); return longest; }