01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1. Example 1:
Input: 0 0 0 0 1 0 0 0 0
Output: 0 0 0 0 1 0 0 0 0
Example 2:
Input: 0 0 0 0 1 0 1 1 1
Output: 0 0 0 0 1 0 1 2 1
Solution: BFS
- We create a array of directions to help updating neighbor nodes
- Push all 0 as start position to queue
- Mark all 1 as INT_MAX
- Start updating neighbors of nodes in queue.
- If neighbor node's value is larger, then we update its value
- Repeat this until the queue is empty
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;
// 1. Push all 0 as start position to queue
// 2. Mark all 1 as INT_MAX
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] = INT_MAX;
}
}
// 2. Start from zeros, update node in all direction
// 3. Update neighbor that has larger values
// 4. Then push valid neighbors to queue
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]) continue;
matrix[x][y] = matrix[t.first][t.second] + 1;
q.push({x, y});
}
}
return matrix;
}