[Algo] 二维前缀和&二维差分
1. 最大的以1为边界的正方形
// 1. 最大的以1为边界的正方形
// https://leetcode.cn/problems/largest-1-bordered-square/description/
int get(vector<vector<int>> &v, int i, int j)
{return (i < 0 || j < 0) ? 0 : v[i][j];
}
void build(vector<vector<int>> &v)
{int n = v.size(), m = v[0].size();for (int i = 0; i < n; i++)for (int j = 0; j < m; j++){v[i][j] += get(v, i, j - 1) + get(v, i - 1, j) - get(v, i - 1, j - 1);}
}
int sum(vector<vector<int>> &v, int a, int b, int c, int d)
{// 返回(a, b) - (c, d)围成的矩形中所有元素的和if (a > c) return 0; // 特别判断边长为2的情况return get(v, c, d) - get(v, c, b - 1) - get(v, a - 1, d) + get(v, a - 1, b - 1);
}
int largest1BorderedSquare(vector<vector<int>>& v) {// 枚举每个正方形-O(n*m*min(n,m)), 利用二维前缀和判断包括外边界的和减去内部和是否等于周长int n = v.size(), m = v[0].size();build(v);if (sum(v, 0, 0, n - 1, m - 1) == 0) return 0;int ans = 1;for (int i = 0; i < n; i++)for (int j = 0; j < m; j++){for (int k = ans + 1, c = i + ans, d = j + ans; c < n && d < m; k++, c++, d++)if (sum(v, i, j, c, d) - sum(v, i + 1, j + 1, c - 1, d - 1) == 4 * (k - 1)) ans = k;}return ans * ans;
}
2. 用邮票贴满网格图
// 2. 用邮票贴满网格图
// https://leetcode.cn/problems/stamping-the-grid/
int get(vector<vector<int>> &v, int i, int j)
{int n = v.size(), m = v[0].size();return (i < 0 || i >= n || j < 0 || j >= m) ? 0 : v[i][j];
}
void build(vector<vector<int>> &v)
{// 生成二维前缀和数组int n = v.size(), m = v[0].size();for (int i = 0; i < n; i++)for (int j = 0; j < m; j++){v[i][j] += get(v, i, j - 1) + get(v, i - 1, j) - get(v, i - 1, j - 1);}
}
int sum(vector<vector<int>> &v, int a, int b, int c, int d)
{// 返回(a, b) - (c, d)围成的矩形中所有元素的和return get(v, c, d) - get(v, c, b - 1) - get(v, a - 1, d) + get(v, a - 1, b - 1);
}
void add(vector<vector<int>> &v, int a, int b, int c, int d)
{// 二维差分int n = v.size(), m = v[0].size();v[a][b] += 1;if (c + 1 < n && d + 1 < m) v[c + 1][d + 1] += 1;if (d + 1 < m) v[a][d + 1] -= 1;if (c + 1 < n) v[c + 1][b] -= 1;
}bool possibleToStamp(vector<vector<int>>& v, int h, int w) {int n = v.size(), m = v[0].size();vector<vector<int>> prefix_sum = v;vector<vector<int>> diff(n, vector<int>(m, 0)); // 初始化为全零数组build(prefix_sum);for (int i = 0; i < n; i++)for (int j = 0; j < m; j++){if (v[i][j] == 0 && i + h - 1 < n && j + w - 1 < m && sum(prefix_sum, i, j, i + h - 1, j + w - 1) == 0)add(diff, i, j, i + h - 1, j + w - 1);}build(diff);for (int i = 0; i < n; i++)for (int j = 0; j < m; j++){if (v[i][j] == 0 && diff[i][j] == 0) return false; // 检查所有空白区域}return true;
}