-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
75 lines (58 loc) · 1.59 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
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
/*
* @lc app=leetcode id=542 lang=javascript
*
* [542] 01 Matrix
*/
// @lc code=start
/**
* @param {number[][]} matrix
* @return {number[][]}
*/
const updateMatrix = (matrix: number[][]): number[][] => {
// * ['200 ms', '60.76 %', '64.4 MB', '100 %']
// * https://medium.com/@silasburger/01-matrix-leetcode-javascript-walkthrough-3747f894092c
// * bfs, boundary check looping
// * ---------------- failed cases, change nothing
if (matrix.length < 1 || matrix[0].length < 1) return matrix;
// * ---------------- preparation
const maxR = matrix.length;
const maxC = matrix[0].length;
// * ---------------- initialize
let checkList: [number, number][] = [];
for (let r = 0; r < maxR; r++) {
for (let c = 0; c < maxC; c++) {
const e = matrix[r][c];
if (e === 0) {
checkList.push([r, c]);
} else {
// * set 1 to Infinity as the mark of unvisited
matrix[r][c] = Infinity;
}
}
}
// * ---------------- bfs
let depthValue = 1;
while (checkList.length) {
const nextCheckList: [number, number][] = [];
checkList.forEach(([x, y]) => {
[
[x + 1, y],
[x - 1, y],
[x, y + 1],
[x, y - 1],
].forEach(([r, c]) => {
const inRange = 0 <= r && r < maxR && 0 <= c && c < maxC;
if (inRange && matrix[r][c] === Infinity) {
matrix[r][c] = depthValue;
nextCheckList.push([r, c]);
}
});
});
checkList = nextCheckList;
depthValue++;
}
// * ---------------- return
return matrix;
};
// @lc code=end
export { updateMatrix };