-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathflood_fill.ts
47 lines (36 loc) · 947 Bytes
/
flood_fill.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
// 733. Flood Fill
// https://leetcode.com/problems/flood-fill/
export default function floodFill(
image: number[][],
startingRow: number,
startingColumn: number,
newColor: number
): number[][] {
let startingColor = image[startingRow][startingColumn];
if (startingColor === newColor) {
return image;
}
const stack: PixelPosition[] = [[startingRow, startingColumn]];
while (stack.length >= 1) {
const [row, column] = stack.pop()!;
if (image[row][column] !== startingColor) {
continue;
}
image[row][column] = newColor;
if (row - 1 >= 0) {
stack.push([row - 1, column]);
}
if (row + 1 < image.length) {
stack.push([row + 1, column]);
}
if (column - 1 >= 0) {
stack.push([row, column - 1]);
}
if (column + 1 < image[0].length) {
stack.push([row, column + 1]);
}
}
return image;
}
// [row, column]
type PixelPosition = [number, number];