Categories
Array Loop Matrix

Spiral Matrix

function spiralMatrix(dimension) {

    let matrix = [];
    // create blank matrix based from given dimension
    for (let i = 0; i < dimension; i++) {
        matrix.push(new Array(dimension).fill(0))
    }

    let counter = 1;
    let startRow = 0, endRow = dimension, startColumn = 0, endColumn = dimension;


    while (startRow < endRow && startColumn < endColumn) {

        // top left -> top right
        for (let i = startColumn; i < endColumn; i++) {
            matrix[startRow][i] = counter++;
        }
        startRow++

        // top right -> bottom right
        for (let i = startRow; i < endRow; i++) {
            matrix[i][endColumn - 1] = counter++;
        }
        endColumn--;

        // bottom right -> bottom left
        for (let i = endColumn - 1; i >= startColumn; i--) {
            matrix[endRow - 1][i] = counter++;
        }
        endRow--;


        // bottom left -> top left
        for (let i = endRow; i > startRow; i--) {
            matrix[i - 1][startColumn] = counter++;
        }
        startColumn++;

    }

     return matrix;
}

Categories
Array Loop Matrix

Game Of Life (Optimized)

let gameOfLife = function(board) {

    if (!board) return [];

    let LIVE = 1,
        DEAD = 0,
        ALIVE_TO_DEAD = 0b01, // [next state, current state]
        ALIVE_TO_ALIVE = 0b11,
        DEAD_TO_ALIVE = 0b10,
        DEAD_TO_DEAD = 0b00,
        maxRow = board.length - 1,
        maxCol = board[0].length - 1;

    function getAdjacentCount(row, col, valueToCompare) {
        let sum = 0;
        for (let i = Math.max(row - 1, 0); i <= Math.min(row + 1, maxRow); i++) {
            for (let j = Math.max(col - 1, 0); j <= Math.min(col + 1, maxCol); j++) {
                if (i === row && j === col) continue;
                if (board[i][j] & 1 === valueToCompare) sum = sum + 1;
            }
        }
        return sum;
    }

    function getNextValue(row, col) {
        const val = board[row][col];
        let liveNeighbors = getAdjacentCount(row, col, LIVE);
        if (val === LIVE) {

            // Any live cell with fewer than two live neighbors dies, as if caused by under-population.
            // Any live cell with more than three live neighbors dies, as if by over-population..
            if (liveNeighbors < 2 || liveNeighbors > 3) {
                return ALIVE_TO_DEAD;
            }
            // Any live cell with two or three live neighbors lives on to the next generation.
            return ALIVE_TO_ALIVE;
        }
        // cell is DEAD
        else {
            // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
            if (liveNeighbors === 3) {
                return DEAD_TO_ALIVE;
            }
            // no condition
            return DEAD_TO_DEAD;
        }
    }

    for (let row = 0; row <= maxRow; row++) {
        for (let col = 0; col <= maxCol;col++) {
            board[row][col] = getNextValue(row, col);
        }
    }

    for (let row = 0; row <= maxRow; row++) {
        for (let col = 0; col <= maxCol;col++) {
            board[row][col] = board[row][col] >> 1;
        }
    }

};
Categories
Array Loop Matrix

Game Of Life

let gameOfLife = function(board) {

if (!board) return [];

let copy = [],
LIVE = 1,
DEAD = 0,
maxRow = board.length - 1,
maxCol = board[0].length - 1;

function getAdjacentCount(row, col, valueToCompare) {
let sum = 0;
for (let i = Math.max(row - 1, 0); i <= Math.min(row + 1, maxRow); i++) {
for (let j = Math.max(col - 1, 0); j <= Math.min(col + 1, maxCol); j++) {
if (i === row && j === col) continue;
if (copy[i] && copy[i][j] !== undefined) {
if (copy[i][j] === valueToCompare) sum = sum + 1; //?
}
else {
if (board[i][j] === valueToCompare) sum = sum + 1; //?
}
}
}
return sum;
}

function getNextValue(row, col) {
const val = board[row][col];
let liveNeighbors = getAdjacentCount(row, col, LIVE);
if (val === LIVE) {

// Any live cell with fewer than two live neighbors dies, as if caused by under-population.
if (liveNeighbors < 2) {
return DEAD;
}
// Any live cell with more than three live neighbors dies, as if by over-population..
else if (liveNeighbors > 3) {
return DEAD;
}
// Any live cell with two or three live neighbors lives on to the next generation.
return LIVE;
}
// cell is DEAD
else {
// Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
if (liveNeighbors === 3) {
return LIVE;
}
// no condition
return DEAD;
}
}

for (let row = 0; row <= maxRow; row++) {
copy[row] = [];
for (let col = 0; col <= maxCol;col++) {
copy[row][col] = board[row][col];
board[row][col] = getNextValue(row, col);
}
}

};
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
Depth First Search Leetcode Loop Matrix Recursion

Number Of Distinct Islands

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

let numRows = grid.length,
numCols = grid[0].length,
LAND = 1, VISITED = 2;

function markAndVisit(row, col, island = [], level = 0) {
if (grid[row][col] === LAND) {
grid[row][col] = VISITED;
island.push('X' + level);

// up
if (row > 0 && grid[row - 1][col] === LAND) {
island.push('U' + level);
markAndVisit(row - 1, col, island, level + 1);
}

// down
if (row < numRows - 1 && grid[row + 1][col] === LAND) {
island.push('D' + level);
markAndVisit(row + 1, col, island, level + 1);
}

// left
if (col > 0 && grid[row][col - 1] === LAND) {
island.push('L' + level);
markAndVisit(row, col - 1, island, level + 1);
}

// right
if (col < numCols - 1 && grid && grid[row][col + 1] === LAND) {
island.push('R' + level);
markAndVisit(row, col + 1, island, level + 1);
}
}

return island;
}

let islands = new Set();
for (let row = 0; row < numRows;row++) {
for (let col = 0; col < numCols;col++) {
if (grid[row][col] === LAND) {
let island = markAndVisit(row, col);
// console.log(island);
if (island.length) islands.add(island.join(''));
}
}
}

// console.table(grid);
return islands.size;
Categories
Array Binary Search Leetcode Recursion

Search Matrix

let searchMatrix = function(matrix, target) {
if(!matrix.length) return false;

function search(startRow, endRow, startCol, endCol) {
console.log(startRow, endRow, startCol, endCol);
let midRow = Math.floor((startRow + endRow) / 2); //?
let midCol = Math.floor((startCol + endCol) / 2); //?


if (startRow < endRow && startCol < endCol) {
const midValue = matrix[midRow][midCol]; //?
if(midValue === target) {
return true;
}
if (midValue < target) {
return search(midRow + 1, endRow, startCol, endCol)
|| search(startRow, endRow, midCol + 1, endCol);
}
else {
return search(startRow, midRow, startCol, endCol)
|| search(startRow, endRow, startCol, midCol);
}
}

return false;
}

return search(0, matrix.length, 0, matrix[0].length);
};