JS/TS

Basis of JavaScript : 

JavaScript Fundamentals

Problem of finding islands in a grid/matrix

function findIslands(grid) {

  const numRows = grid.length;

  const numCols = grid[0].length;

  const visited = new Array(numRows).fill().map(() => new Array(numCols).fill(false));

  let numIslands = 0;


  function dfs(row, col) {

    if (row < 0 || row >= numRows || col < 0 || col >= numCols || visited[row][col] || grid[row][col] === 0) {

      return;

    }


    visited[row][col] = true;


    dfs(row - 1, col);

    dfs(row + 1, col);

    dfs(row, col - 1);

    dfs(row, col + 1);

  }


  for (let row = 0; row < numRows; row++) {

    for (let col = 0; col < numCols; col++) {

      if (!visited[row][col] && grid[row][col] === 1) {

        numIslands++;

        dfs(row, col);

      }

    }

  }


  return numIslands;

}


// Example usage

const grid = [  [1, 1, 0, 0, 0],

  [1, 1, 0, 0, 0],

  [0, 0, 1, 0, 0],

  [0, 0, 0, 1, 1],

];


console.log(findIslands(grid)); // Outputs: 3