DEV Community 👩‍💻👨‍💻

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Number of Island - I

/**
 * @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

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.