Skip to content

Commit 8ef7d4b

Browse files
committed
add: number of islands
1 parent d02ead8 commit 8ef7d4b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

number-of-islands/HerrineKim.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {number}
4+
*/
5+
var numIslands = function (grid) {
6+
if (!grid || grid.length === 0) return 0;
7+
8+
const rows = grid.length;
9+
const cols = grid[0].length;
10+
let islandCount = 0;
11+
12+
const dfs = (row, col) => {
13+
if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] === '0') {
14+
return;
15+
}
16+
17+
grid[row][col] = '0';
18+
19+
dfs(row - 1, col);
20+
dfs(row + 1, col);
21+
dfs(row, col - 1);
22+
dfs(row, col + 1);
23+
};
24+
25+
for (let i = 0; i < rows; i++) {
26+
for (let j = 0; j < cols; j++) {
27+
if (grid[i][j] === '1') {
28+
islandCount++;
29+
dfs(i, j);
30+
}
31+
}
32+
}
33+
34+
return islandCount;
35+
};

0 commit comments

Comments
 (0)