-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdateMatrix.cpp
More file actions
32 lines (30 loc) · 893 Bytes
/
updateMatrix.cpp
File metadata and controls
32 lines (30 loc) · 893 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
31
32
class Solution {
public:
vector < vector < int >> updateMatrix(vector < vector < int >> & mat) {
int n = mat.size(), m = mat[0].size();
vector<vector<int> > dp(n, vector<int>(m, INT_MAX - 1));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (mat[i][j] == 0)
dp[i][j] = 0;
else {
if (j > 0)
dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1);
if (i > 0)
dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1);
}
}
}
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
if (mat[i][j] != 0) {
if (j < m - 1)
dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1);
if (i < n - 1)
dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1);
}
}
}
return dp;
}
};