leetcode

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

1314.cpp (1210B)


      1 class Solution {
      2     inline int clamp(const int a, const int x, const int y) { return min(max(a, x), y); }
      3 
      4   public:
      5     vector<vector<int>> matrixBlockSum(vector<vector<int>> &mat, int k) {
      6         int n = mat.size(), m = mat[0].size();
      7         vector<vector<int>> dp(n, vector<int>(m, 0)), res(n, vector<int>(m, 0));
      8 
      9         for (int i = 0, sum = 0; i < n; i++)
     10             sum = dp[i][0] = mat[i][0] + sum;
     11         for (int i = 0, sum = 0; i < m; i++)
     12             sum = dp[0][i] = mat[0][i] + sum;
     13         for (int i = 1; i < n; i++) {
     14             for (int j = 1; j < m; j++) {
     15                 dp[i][j] = mat[i][j] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1];
     16             }
     17         }
     18 
     19         for (int i = 0; i < n; i++) {
     20             for (int j = 0; j < m; j++) {
     21                 int x1 = clamp(i - k, 0, n - 1), y1 = clamp(j - k, 0, m - 1);
     22                 int x2 = clamp(i + k, 0, n - 1), y2 = clamp(j + k, 0, m - 1);
     23                 res[i][j] = dp[x2][y2];
     24                 if (x1 > 0) res[i][j] -= dp[x1 - 1][y2];
     25                 if (y1 > 0) res[i][j] -= dp[x2][y1 - 1];
     26                 if (x1 > 0 && y1 > 0) res[i][j] += dp[x1 - 1][y1 - 1];
     27             }
     28         }
     29 
     30         return res;
     31     }
     32 };