Number of Islands

August 21, 2023

DSA & Leetcodes

Number of Islands

Thuta Sann

Thuta Sann

Number of Islands LeetCode solution


Share This Snippet To :

NUMBER OF ISLANDS

Question

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 surrounded by water.

Lets Translate that.

  • You are given a two dimensional grid.
  • You have lot of ones and lot of zeros.
  • Any of the ones that are connected horizontally or vertically, That is an island.
  • Anything with zeros, that's water.
  • Island cannot be connected diagonally.

Lets Take a look at code!

/** * Number of Island * @param { string[][] } grid - Two Dimensional Array * @returns { number } */ export function numsIslands (grid: string[][]) : number { let countIslands = 0; for(let rowIndex in grid){ for (let colIndex in grid[rowIndex]){ console.log('grid[rowIndex][colIndex]', grid[rowIndex][colIndex]) if(grid[rowIndex][colIndex] === '1'){ countIslands++; teraform(parseInt(rowIndex), parseInt(colIndex), grid) } } } return countIslands; } /** * Helper: Convert stuff arround us to Water */ const teraform = (rowIn: number, colIn : number, grid : string[][]) : void => { if(grid[rowIn] === undefined || grid[rowIn][colIn] === undefined || grid[rowIn][colIn] === '0') return; grid[rowIn][colIn] = '0'; teraform(rowIn + 1, colIn, grid); // top teraform(rowIn - 1, colIn, grid); // bottom teraform(rowIn, colIn + 1, grid); // right teraform(rowIn, colIn - 1, grid); // left } // ---- Result console.log('Number of Islands', numsIslands([["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]])); // ---- Result ==> 3

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?