-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
50 lines (40 loc) · 1.02 KB
/
solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { Grid } from './types';
/*
* @lc app=leetcode id=200 lang=javascript
*
* [200] Number of Islands
*/
// @lc code=start
/**
* @param {character[][]} grid
* @return {number}
*/
const numIslands = (grid: Grid): number => {
// * DFS ['60 ms', '90.61 %', '37.5 MB', '74.19 %']
// * https://leetcode.com/problems/number-of-islands/discuss/391717/JavaScript-DFS-56ms-very-easy-to-understand
if (!grid.length) return 0;
const row = grid.length;
const col = grid[0].length;
const dfsWipeout = (r: number, c: number): void => {
if (r < 0 || r >= row || c < 0 || c >= col) return;
if (grid[r][c] === '0') return;
// * wipe island part
grid[r][c] = '0';
dfsWipeout(r + 1, c);
dfsWipeout(r - 1, c);
dfsWipeout(r, c + 1);
dfsWipeout(r, c - 1);
};
let count = 0;
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
if (grid[i][j] === '1') {
count++;
dfsWipeout(i, j);
}
}
}
return count;
};
// @lc code=end
export { numIslands };