LeetCode 542
01 Matrix
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
vector<pair<int, int>> res = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
queue<pair<int, int>> q;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size(); j++) {
if (matrix[i][j] == 0) q.push({i, j});
else matrix[i][j] = INT_MAX;
}
}
while(!q.empty()) {
pair<int, int> t = q.front();
q.pop();
for (int i = 0; i < res.size(); i++) {
int x = t.first+res[i].first;
int y = t.second+res[i].second;
if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() ||matrix[x][y]<=matrix[t.first][t.second]) continue;
matrix[x][y] = matrix[t.first][t.second]+1;
q.push({x, y});
}
}
return matrix;
}
};