leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0542.cpp (1140B)


      1 class Solution {
      2     int m, n;
      3     vector<pair<int, int>> offset = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
      4 
      5     int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; }
      6 
      7   public:
      8     vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {
      9         m = mat.size();
     10         n = mat[0].size();
     11 
     12         vector<vector<int>> res(m, vector<int>(n, INT_MAX));
     13         queue<pair<int, int>> q;
     14 
     15         for (int i = 0; i < m; i++) {
     16             for (int j = 0; j < n; j++) {
     17                 if (mat[i][j] == 0) {
     18                     res[i][j] = 0;
     19                     q.push({i, j});
     20                 }
     21             }
     22         }
     23 
     24         while (!q.empty()) {
     25             auto [sr, sc] = q.front();
     26             q.pop();
     27             for (auto &p : offset) {
     28                 int nsr = sr + p.first;
     29                 int nsc = sc + p.second;
     30                 if (valid(nsr, nsc)) {
     31                     if (res[nsr][nsc] > res[sr][sc] + 1) {
     32                         res[nsr][nsc] = res[sr][sc] + 1;
     33                         q.push({nsr, nsc});
     34                     }
     35                 }
     36             }
     37         }
     38 
     39         return res;
     40     }
     41 };