Skip to content

Commit 33da287

Browse files
committed
Add solution #542
1 parent 4f7a148 commit 33da287

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@
117117
500|[Keyboard Row](./0500-keyboard-row.js)|Easy|
118118
506|[Relative Ranks](./0506-relative-ranks.js)|Easy|
119119
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
120+
542|[01 Matrix](./0542-01-matrix.js)|Medium|
120121
551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy|
121122
557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy|
122123
565|[Array Nesting](./0565-array-nesting.js)|Medium|

solutions/0542-01-matrix.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 542. 01 Matrix
3+
* https://leetcode.com/problems/01-matrix/
4+
* Difficulty: Medium
5+
*
6+
* Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
7+
*
8+
* The distance between two adjacent cells is 1.
9+
*/
10+
11+
/**
12+
* @param {number[][]} matrix
13+
* @return {number[][]}
14+
*/
15+
var updateMatrix = function(matrix) {
16+
const queue = [];
17+
18+
for (let i = 0; i < matrix.length; i++) {
19+
for (let j = 0; j < matrix[0].length; j++) {
20+
if (matrix[i][j] === 0) {
21+
queue.push([i, j, 0]);
22+
} else {
23+
matrix[i][j] = Infinity;
24+
}
25+
}
26+
}
27+
28+
29+
while (queue.length) {
30+
const [i, j, k] = queue.shift();
31+
if (matrix[i][j] > k) {
32+
matrix[i][j] = k;
33+
}
34+
[[-1, 0], [1, 0], [0, -1], [0, 1]].forEach(p => {
35+
const [x, y, z] = [i + p[0], j + p[1], k + 1];
36+
if (x > -1 && x < matrix.length && y > -1 && y < matrix[0].length) {
37+
if (matrix[x][y] === Infinity) {
38+
queue.push([x, y, z]);
39+
}
40+
}
41+
});
42+
}
43+
44+
return matrix;
45+
};

0 commit comments

Comments
 (0)