Skip to content

Commit 0481373

Browse files
committed
graph - bfs iter O(rc) O(1)
1 parent f90dc7f commit 0481373

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

leetcode-542-01Matrix-2.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {number[][]} mat
3+
* @return {number[][]}
4+
*/
5+
6+
// p: grid m x n;
7+
// r: grid m x n;
8+
// e:
9+
//
10+
//
11+
// [[0,0,0],
12+
// [0,1,0],
13+
// [1,1,1]]
14+
//
15+
//
16+
17+
var updateMatrix = function (mat) {
18+
const queue = [];
19+
for (let i = 0; i < mat.length; i++) {
20+
for (let j = 0; j < mat[0].length; j++) {
21+
if (mat[i][j] === 0) {
22+
queue.push([i, j, 0]);
23+
} else {
24+
mat[i][j] = -1;
25+
}
26+
}
27+
}
28+
29+
while (queue.length > 0) {
30+
const [y, x, d] = queue.shift();
31+
const deltas = [
32+
[y + 1, x],
33+
[y - 1, x],
34+
[y, x + 1],
35+
[y, x - 1],
36+
];
37+
for (let [neiY, neiX] of deltas) {
38+
const boundY = 0 <= neiY && neiY < mat.length;
39+
const boundX = 0 <= neiX && neiX < mat[0].length;
40+
41+
if (boundY && boundX && mat[neiY][neiX] === -1) {
42+
mat[neiY][neiX] = d + 1;
43+
queue.push([neiY, neiX, d + 1]);
44+
}
45+
}
46+
}
47+
48+
return mat;
49+
};

0 commit comments

Comments
 (0)