-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01matrix542.cpp
More file actions
77 lines (67 loc) · 2.4 KB
/
01matrix542.cpp
File metadata and controls
77 lines (67 loc) · 2.4 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int maxdist = m+n;
int dr[]= {0, 0 , 1, -1};
int dc[]= {1, -1, 0, 0};
queue<pair<int,int>>q;
//vector<vector<int>> res(matrix.size(), vector<int>(matrix[0].size(),maxdist));
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]= maxdist;
}
}
while(!q.empty()){
auto curr = q.front();
q.pop();
//traverse the neighbors
for(int i = 0; i<4; i++){
int nextr = curr.first + dr[i];
int nextc = curr.second + dc[i];
if(nextr>=0 && nextr<m && nextc>=0 && nextc<n && matrix[curr.first][curr.second]+1< matrix[nextr][nextc]){
q.push({nextr, nextc});
matrix[nextr][nextc] = matrix[curr.first][curr.second]+1;
}
}
}
return matrix;
}
};
//my method
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
vector<vector<int>>ans(matrix);
pair<int,int>coordinate;
vector<pair<int,int>>target;
int distance , min = INT_MAX;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (matrix[i][j] == 0) {
coordinate.first = i;
coordinate.second = j;
target.push_back(coordinate);
}
}
}
//find 0 to 1 distance
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (matrix[i][j] == 1) {
min = INT_MAX;
for (int k = 0; k < target.size(); k++) {
distance = abs(target[k].first - i) + abs(target[k].second - j);
if (min > distance) min = distance;
}
ans[i][j] = min;
}
}
}
return ans;
}
};