-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path542. 01 Matrix.cpp
More file actions
30 lines (30 loc) · 964 Bytes
/
542. 01 Matrix.cpp
File metadata and controls
30 lines (30 loc) · 964 Bytes
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
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix)
{
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
queue<pair<int, int>> q;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (matrix[i][j] == 0)
q.push({i, j});
else matrix[i][j] = -1;
}
}
while (!q.empty())
{
auto t = q.front(); q.pop();
for (auto dir : dirs) {
int x = t.first + dir[0], y = t.second + dir[1];
if (x < 0 || x >= m || y < 0 || y >= n ||(matrix[x][y] <= matrix[t.first][t.second]&&matrix[x][y]!=-1))
continue;
matrix[x][y] = matrix[t.first][t.second] + 1;
q.push({x, y});
}
}
return matrix;
}
};