|
| 1 | +using loc = pair<int, int>; |
| 2 | +int dx[] = {1, -1, 0, 0}; |
| 3 | +int dy[] = {0, 0, 1, -1}; |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { |
| 7 | + int n = mat.size(), m = mat[0].size(); |
| 8 | + |
| 9 | + vector<vector<int>> dis(n, vector<int>(m, INT_MAX)); |
| 10 | + // dis[i][j] = nearest distance (i, j) to nearest 0 |
| 11 | + |
| 12 | + queue<loc> q; |
| 13 | + for(int i = 0; i < n; i++) { |
| 14 | + for(int j = 0; j < m; j++) { |
| 15 | + if (mat[i][j] == 0) { |
| 16 | + q.push({i, j}); |
| 17 | + dis[i][j] = 0; |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + while(!q.empty()) { |
| 23 | + // loc cur = q.front(); |
| 24 | + // int x = cur.first, y = cur.second; |
| 25 | + auto [x, y] = q.front(); // current loc in mat, structured binding in C++ |
| 26 | + q.pop(); |
| 27 | + // (2,3) -> (1, 3) up, (3, 3) down, +1 -1 on the columns as well |
| 28 | + for(int k = 0; k < 4; k++) { |
| 29 | + int nx = x + dx[k], ny = y + dy[k]; |
| 30 | + if (0 <= nx && nx < n && 0 <= ny && ny < m) { |
| 31 | + // valid neighbour |
| 32 | + if (dis[nx][ny] == INT_MAX) { |
| 33 | + dis[nx][ny] = 1 + dis[x][y]; |
| 34 | + q.push({nx, ny}); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return dis; |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +/* |
| 45 | +// BFS gives the shortest path in unweighted graphs |
| 46 | +
|
| 47 | +n * m <--- 0s and 1s |
| 48 | + |
| 49 | + for every 1: |
| 50 | + compute the smallest distance to 0 |
| 51 | + |
| 52 | +dis[i][j] = 0 where mat[i][j] = 0 |
| 53 | + |
| 54 | +queue<> Q = {(i,j)} where mat[i][j] = 0; |
| 55 | +
|
| 56 | +cur = Q.front(); |
| 57 | +
|
| 58 | +for(nei in neighbors(cur)) { |
| 59 | + dis[nei] = 1 + dis[cur] if nei is not alreaady in queue |
| 60 | +} |
| 61 | +
|
| 62 | +*/ |
| 63 | + |
0 commit comments