Skip to content

Instantly share code, notes, and snippets.

@tdubs42
Last active February 19, 2024 01:32
Show Gist options
  • Save tdubs42/737208025b00f01eff7a69bb35785892 to your computer and use it in GitHub Desktop.
Save tdubs42/737208025b00f01eff7a69bb35785892 to your computer and use it in GitHub Desktop.
Number of Islands - JavaScript
const numIslands = grid => {
// need variable to count islands
let islands = 0
// create a function to search for 1 and use recursion to search surrounding cells
const findIslands = (row, col, grid) => {
// first check if row and col exist on grid and if grid[row][col] 0
if (
row < 0 ||
col < 0 ||
row > grid.length - 1 ||
col > grid[row].length - 1 ||
grid[row][col] === '0'
) {
return
}
// use recursion to search surrounding cells
grid[row][col] = '0'
findIslands(row - 1, col, grid)
findIslands(row, col - 1, grid)
findIslands(row + 1, col, grid)
findIslands(row, col + 1, grid)
}
// use forEach to loop through grid and use findIslands function
grid.forEach((row, index) => {
row.forEach((value, i) => {
// check if value === '1' and if so, use findIslands to check surrounding cells
if (value === '1') {
findIslands(index, i, grid)
islands ++
}
})
})
// return number of islands
return islands
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment