01 Matrix LeetCode solution in C++

1
class Solution {
2
public:
3
vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {
4
queue<pair<int, int>> q;
5
for (int i = 0; i < mat.size(); i++) {
6
for (int j = 0; j < mat[0].size(); j++) {
7
if (mat[i][j] == 0)
8
q.push({i, j});
9
else
10
mat[i][j] = -1;
11
}
12
}
13
int length = 0;
14
int dirx[] = {1, -1, 0, 0};
15
int diry[] = {0, 0, 1, -1};
16
while (!q.empty()) {
17
int size = q.size();
18
length++;
19
while (size--) {
20
auto f = q.front();
21
q.pop();
22
int s = f.first;
23
int end = f.second;
24
for (int i = 0; i < 4; i++) {
25
int r = s + dirx[i];
26
int c = end + diry[i];
27
if (r < 0 || c < 0 || r == mat.size() || c == mat[0].size() || mat[r][c] != -1) continue;
28
mat[r][c] = length;
29
q.push({r, c});
30
}
31
}
32
}
33
return mat;
34
}
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0