Number of Island - I

ZeeshanAli-0704 - Sep 24 '22 - - Dev Community
/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
  let rows = grid.length;
  let cols = grid[0].length;
  let numberOfIsland = 0;

  if (rows.length === 0) {
    return 0;
  }

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (grid[i][j] === "1") {
        markIsland(i, j, grid, rows, cols);
        numberOfIsland++;
      }
    }
  }
  return numberOfIsland;
};

const markIsland = (i, j, grid, rows, cols) => {
  if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] !== "1") {
    return;
  }
  grid[i][j] = 2;
  markIsland(i + 1, j, grid, rows, cols);
  markIsland(i - 1, j, grid, rows, cols);
  markIsland(i, j + 1, grid, rows, cols);
  markIsland(i, j - 1, grid, rows, cols);
};

console.log(
  numIslands([
    ["1", "1", "1", "1", "0"],
    ["1", "1", "0", "1", "0"],
    ["1", "1", "0", "0", "0"],
    ["0", "0", "0", "0", "0"],
  ])
);

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player