Skip to content

Commit b598d06

Browse files
authored
Create 200-number-of-islands.js
1 parent 8b4ad2a commit b598d06

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

200-number-of-islands.js

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

0 commit comments

Comments
 (0)