2
* @param {character[][]} grid5
var numIslands = function (grid) {14
for (let rowIndex = 0; rowIndex < grid.length; rowIndex++) {15
for (let colIndex = 0; colIndex < grid[0].length; colIndex++) {16
const node = grid[rowIndex][colIndex];18
// Don't bother with water19
if (node === "0") continue;21
// Once we encounter land, try to get all22
// the connected land from the current land.23
// Once we get all the land connected from24
// the current land, mark them as water so25
// that it would disregarded by the main loop.28
const connectedLandStack = [[rowIndex, colIndex]];30
while (connectedLandStack.length > 0) {31
const [row, col] = connectedLandStack.pop();33
// change the land to water36
for (const direction of directions) {37
// To get all the connected land we need to check38
// all directions (left, right, top, bottom)39
const newNode = [row + direction[0], col + direction[1]];40
const newNodeValue = grid[newNode[0]]?.[newNode[1]];42
// We only care about the connected lands43
if (newNodeValue === undefined || newNodeValue === "0") {47
connectedLandStack.push(newNode);