JSFiddle - React, Tailwind, and code Playground

by Steven Senkus

JavaScript

/**
Given a 2d grid map of '1's (land) and '0's (water), count 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.

*/


var numIslands = function(grid) {
  let islandCount = 0;

  if (grid === null || grid.length === 0) return islandCount;

  function dfs(i, j, grid) {
    if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] === 0) {
      return 0;
    }

    grid[i][j] = 0;
    dfs(i + 1, j, grid);
    dfs(i - 1, j, grid);
    dfs(i, j + 1, grid);
    dfs(i, j - 1, grid);
    return 1;
  }



  for (let i = 0; i < grid.length; i++) {

    for (let j = 0; j < grid[i].length; j++) {
      if (grid[i][j] === 1) {
        islandCount += dfs(i, j, grid)
      }
    }

  }

  console.log(islandCount);
  return islandCount;
}


const testGrids = [{
    grid: [
      [1, 1, 1, 1, 0],
      [1, 1, 0, 1, 0],
      [1, 1, 0, 0, 0],
      [0, 0, 0, 0, 0]
    ],
    expected: 1
  },
  {
    grid: [
      [1, 1, 1, 1, 0],
      [1, 1, 0, 1, 0],
      [1, 1, 0, 0, 0],
      [0, 0, 0, 0, 0]
    ],

    expected: 1
  }
];

console.log(numIslands(testGrids[0].grid) === testGrids[0].expected);
console.log(numIslands(testGrids[1].grid) === testGrids[1].expected);