-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxDistance.ts
80 lines (63 loc) · 1.76 KB
/
maxDistance.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
75
76
77
78
79
80
import { dx, dy } from 'constants/directions'
// <Recursion, BFS>
// Time: O(n^2)
// Space: O(n^2)
class MyMap {
private grid: number[][]
private n: number
private queue: [number, number][]
public constructor(grid: number[][]) {
this.grid = grid
this.n = grid.length
this.queue = []
}
private addLands() {
for (let i = 0; i < this.n; ++i) {
for (let j = 0; j < this.n; ++j) {
// land
if (this.grid[i][j] === 1) {
this.queue.push([i, j])
}
}
}
}
// 1. bfs
public bfs(): number {
let maxDistance = -1
this.addLands()
// edge cases
if (!this.queue.length || this.queue.length === this.n ** 2) {
return maxDistance
}
while (this.queue.length) {
const length = this.queue.length
for (let i = 0; i < length; ++i) {
const [x, y] = this.queue.shift()!
for (let j = 0; j < this.n; ++j) {
const [px, py] = [x + dx[j], y + dy[j]]
if (
px >= 0 &&
px < this.n &&
py >= 0 &&
py < this.n &&
this.grid[px][py] === 0
) {
this.grid[px][py] = -1
this.queue.push([px, py])
}
}
}
++maxDistance
}
return maxDistance
}
}
function maxDistance(grid: number[][]): number {
// edge cases
if (!grid.length) {
return -1
}
const myMap = new MyMap(grid)
return myMap.bfs()
}
export { maxDistance }