Number of Islands LeetCode solution in JavaScript

1
/**
2
* @param {character[][]} grid
3
* @return {number}
4
*/
5
var numIslands = function (grid) {
6
const directions = [
7
[1, 0],
8
[0, 1],
9
[-1, 0],
10
[0, -1],
11
];
12
let islandCount = 0;
13

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];
17

18
// Don't bother with water
19
if (node === "0") continue;
20

21
// Once we encounter land, try to get all
22
// the connected land from the current land.
23
// Once we get all the land connected from
24
// the current land, mark them as water so
25
// that it would disregarded by the main loop.
26
islandCount++;
27

28
const connectedLandStack = [[rowIndex, colIndex]];
29

30
while (connectedLandStack.length > 0) {
31
const [row, col] = connectedLandStack.pop();
32

33
// change the land to water
34
grid[row][col] = "0";
35

36
for (const direction of directions) {
37
// To get all the connected land we need to check
38
// all directions (left, right, top, bottom)
39
const newNode = [row + direction[0], col + direction[1]];
40
const newNodeValue = grid[newNode[0]]?.[newNode[1]];
41

42
// We only care about the connected lands
43
if (newNodeValue === undefined || newNodeValue === "0") {
44
continue;
45
}
46

47
connectedLandStack.push(newNode);
48
}
49
}
50
}
51
}
52

53
return islandCount;
54
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0