题目
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.
给定一个由0和1组成的矩阵,找到每个单元和最近的0的距离。
两个相邻单元的距离是1。
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.
代码
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
bool valid(vector<vector<int>> & matrix, int m, int n, int i, int j, int val) {
return i >= 0 && i < m&&j >= 0 && j < n&&matrix[i][j] == val;
}
vector<vector<int>> updateMatrix(vector<vector<int>> & matrix) {
int rows = matrix.size();
if (rows == 0) {
return matrix;
}
int cols = matrix[0].size();
vector<vector<int>> dist(rows, vector<int>(cols, INT_MAX));
for (int i = 0; i<rows; i++) {
for (int j = 0; j<cols; j++) {
dist[i][j] = matrix[i][j];
}
}
int val = 0;
bool idx = true;
while (idx) {
int next = val + 1;
int last = next + 1;
idx = false;
for (int i = 0; i<rows; i++) {
for (int j = 0; j<cols; j++) {
if (dist[i][j] >= next) {
if (valid(dist, rows, cols, i - 1, j, val) || valid(dist, rows, cols, i + 1, j, val) || valid(dist, rows, cols, i, j - 1, val) || valid(dist, rows, cols, i, j + 1, val)) {
dist[i][j] = next;
}
else {
dist[i][j] = last;
}
idx = true;
}
}
}
val = val + 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cout << dist[i][j] << '\t';
}
cout << endl;
}
}
return dist;
}
};
int main(){
vector<vector<int>> src(5, vector<int>(5,1));
src[2][2] = 0;
Solution so;
vector<vector<int>> dist = so.updateMatrix(src);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cout << dist[i][j] << '\t';
}
cout << endl;
}
}