-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathislandPerimeter.ts
74 lines (57 loc) · 1.49 KB
/
islandPerimeter.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { dx, dy } from 'constants/directions'
// <Recursion, DFS>
// Time: O(nm)
// Space: O(nm)
class MyMap {
private grid: number[][]
private n: number
private m: number
private perimeter: number
public constructor(grid: number[][]) {
this.grid = grid
this.n = grid.length
this.m = grid[0].length
this.perimeter = 0
}
// 1. dfs
private dfs(x: number, y: number): number {
// out of boundary or sea
if (x < 0 || x >= this.n || y < 0 || y >= this.m || !this.grid[x][y]) {
return 1
}
// visited
if (this.grid[x][y] === -1) {
return 0
}
this.grid[x][y] = -1 // mark as visited
let sides = 0
for (let i = 0; i < 4; ++i) {
const [px, py] = [x + dx[i], y + dy[i]]
sides += this.dfs(px, py)
}
return sides
}
public countPerimeter() {
for (let i = 0; i < this.n; ++i) {
for (let j = 0; j < this.m; ++j) {
// land
if (this.grid[i][j]) {
this.perimeter += this.dfs(i, j)
}
}
}
}
public getPerimeter(): number {
return this.perimeter
}
}
function islandPerimeter(grid: number[][]): number {
// edge cases
if (!grid.length) {
return 0
}
const myMap = new MyMap(grid)
myMap.countPerimeter()
return myMap.getPerimeter()
}
export { islandPerimeter }