Skip to content

Commit 03fbcef

Browse files
committed
number of islands solved
1 parent d964d70 commit 03fbcef

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

number-of-islands/hsskey.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {number}
4+
*/
5+
var numIslands = function(grid) {
6+
if (!grid.length) return 0;
7+
8+
const rows = grid.length;
9+
const cols = grid[0].length;
10+
const visit = new Set();
11+
let islands = 0;
12+
13+
const bfs = (r, c) => {
14+
const queue = [];
15+
queue.push([r, c]);
16+
visit.add(`${r},${c}`);
17+
18+
while (queue.length) {
19+
const [row, col] = queue.shift();
20+
const directions = [
21+
[1, 0],
22+
[-1, 0],
23+
[0, 1],
24+
[0, -1],
25+
];
26+
27+
for (const [dr, dc] of directions) {
28+
const newRow = row + dr;
29+
const newCol = col + dc;
30+
31+
if (
32+
newRow >= 0 &&
33+
newRow < rows &&
34+
newCol >= 0 &&
35+
newCol < cols &&
36+
grid[newRow][newCol] === '1' &&
37+
!visit.has(`${newRow},${newCol}`)
38+
) {
39+
queue.push([newRow, newCol]);
40+
visit.add(`${newRow},${newCol}`);
41+
}
42+
}
43+
}
44+
};
45+
46+
for (let r = 0; r < rows; r++) {
47+
for (let c = 0; c < cols; c++) {
48+
if (grid[r][c] === '1' && !visit.has(`${r},${c}`)) {
49+
bfs(r, c);
50+
islands += 1;
51+
}
52+
}
53+
}
54+
55+
return islands;
56+
};

0 commit comments

Comments
 (0)