Journal Archive

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
    // simple case
    if (!grid || grid.length === 0) return 0;
    
    let m = grid.length;
    let n = grid[0].length;
    let islandCount = 0;
    
    // helper function BFS search on connected lands
    const removeLand = (r,c, grid) => {
        // four directions
        const directions = [[1,0],[-1,0],[0,1],[0,-1]];
        let q = [];
        q.push([r,c]);
        
        while (q.length !== 0) {
            let [cRow, cColumn] = q.shift();
            directions.forEach(([dy, dx]) => {
                dy += cRow;
                dx += cColumn;
                if (dy < 0 || dx < 0 || dy >= m || dx >= n || grid[dy][dx] !== "1") return;
                
                grid[dy][dx] = "#";
                q.push([dy, dx]);
            })
        }
    }
    
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (grid[i][j] === "1") {
                grid[i][j] = "#";
                removeLand(i, j, grid);
                islandCount++;
            }
        }
    }
    
    return islandCount;
    
    
};

Day 47: Solving one of LeetCode problems

200. Number of Islands Difficulty - Medium

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

 

Example 1:

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1
		

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3