程式語言 - LeetCode - C++ - 3212. Count Submatrices With Equal Frequency of X and Y



參考資訊:
https://algo.monster/liteproblems/3212

題目:


方法:

Dynamic Programming

解答:

class Solution {
public:
    int numberOfSubmatrices(vector<vector<char>>& grid) {
        int r = 0;
        int row_size = grid.size();
        int col_size = grid[0].size();
        vector<vector<int>> sx(row_size + 1, vector<int>(col_size + 1, 0));
        vector<vector<int>> sy(row_size + 1, vector<int>(col_size + 1, 0));

        for (int i = 1; i <= row_size; ++i) {
            for (int j = 1; j <= col_size; ++j) {
                sx[i][j] = sx[i - 1][j] + sx[i][j - 1];
                sx[i][j] -= sx[i - 1][j - 1];
                sx[i][j] += (grid[i - 1][j - 1] == 'X' ? 1 : 0);

                sy[i][j] = sy[i - 1][j] + sy[i][j - 1];
                sy[i][j] -= sy[i - 1][j - 1];
                sy[i][j] += (grid[i - 1][j - 1] == 'Y' ? 1 : 0);

                if (sx[i][j] && (sx[i][j] == sy[i][j])) {
                    r += 1;
                }
            }
        }

        return r;
    }
};