Categories
Array Dynamic Programming Leetcode

Unique Paths with Obstacles

let uniquePathsWithObstacles = function(obstacleGrid) {

if (!obstacleGrid || !obstacleGrid.length) return 0;

function markNextRowsAsZero(col) {
for (let i = col; i < maxCol; i++) {
obstacleGrid[0][i] = 0;
}
}
function markNextColumnsAsZero(row) {
for (let i = row; i < maxRow; i++) {
obstacleGrid[i][0] = 0;
}
}

let maxRow = obstacleGrid.length,
maxCol = obstacleGrid[0].length,
OBSTACLE = 1, VISITED = -1;

// first block is obstacle return 0;
if (obstacleGrid[0][0] === OBSTACLE) {
return 0;
}

// mark all first rows as either 1 or zero
for (let col = 0; col < maxCol;col++) {
if (obstacleGrid[0][col] === OBSTACLE) {
markNextRowsAsZero(col);
break;
}
else {
obstacleGrid[0][col] = 1;
}
}

// mark all first columns as either 1 or zero
for (let row = 1; row < maxRow;row++) {
if (obstacleGrid[row][0] === OBSTACLE) {
markNextColumnsAsZero(row);
break;
}
else {
obstacleGrid[row][0] = 1;
}
}

for (let row = 1; row < maxRow;row++) {
for (let col = 1; col < maxCol;col++) {
if (obstacleGrid[row][col] === OBSTACLE) {
obstacleGrid[row][col] = 0;
}
else {
obstacleGrid[row][col] =
obstacleGrid[row - 1][col] +
obstacleGrid[row][col - 1];
}

}
}

return obstacleGrid[maxRow - 1][maxCol - 1];
};
Categories
Dynamic Programming Leetcode Loop

Unique Paths (Iterative)

let uniquePaths = function(m, n) {

let getKey = (row, col) => `${row}${col}`;

let cache = { }
for (let row = 1; row <= m; row++) {
for (let col = 1; col <= n; col++) {
if (row === 1) {
cache[getKey(row, col)] = 1;
}
else if (col === 1) {
cache[getKey(row, col)] = 1;
}
else {
cache[getKey(row, col)] = cache[getKey(row-1, col)] + cache[getKey(row, col - 1)];
}
}
}

return cache[getKey(m,n)];
};
Categories
Array Dynamic Programming Leetcode

Minimum Path Sum (Iterative)

let minPathSum = function(grid) {

    if(!grid || !grid.length) return 0;

    let maxRow = grid.length, maxCol = grid[0].length;
    
    for (let row = 0; row < maxRow;row++) {
        for (let col = 0; col < maxCol;col++) {
            console.log(row, col);
            if (row === 0) {
                grid[row][col] = grid[row][col] + (grid[row][col - 1] || 0);
            }
            else if (col === 0) {
                grid[row][col] = grid[row][col] + grid[row - 1][col];
            } else {
                grid[row][col] = Math.min(
                    grid[row][col] + grid[row - 1][col], // top
                    grid[row][col] + grid[row][col - 1] // left
                );
            }
        }
    }
    return grid[maxRow - 1][maxCol - 1];
};
Categories
Dynamic Programming Leetcode Recursion

Fibonacci (Recursion)

function fib(x) {
    let cache = {}
    function fibInternal(n) {
        if(n == 0) return 0;
        if(n <= 2) return 1;
        if (cache[n]) return cache[n];

        const result = fibInternal(n - 1) + fibInternal(n - 2);
        cache[n] = result;
        return result;
    }

    return fibInternal(x)
}