Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.3 kB
2
Indexable
Never
class Solution {
public:
    bool isMagic(int r, int c, vector<vector<int>>& grid) {
        int freq[9] = {};
        int row_sum[3] = {};
        int col_sum[3] = {};

        for (int i = r; i < r + 3; i++) {
            for (int j = c; j < c + 3; j++) {
                int val = grid[i][j];

                // Check distinct value
                if (val < 1 || val > 9 || ++freq[val-1] > 1)
                    return false;

                row_sum[i-r] += val;
                col_sum[j-c] += val;
            }
        }

        for (int i = 0; i < 3; i++) {
            if (row_sum[i] != 15 || col_sum[i] != 15)
                return false;
        }

        if (grid[r][c] + grid[r+1][c+1] + grid[r+2][c+2] != 15)
            return false;
        if (grid[r][c+2] + grid[r+1][c+1] + grid[r+2][c] != 15)
            return false;

        return true;
    }

    int numMagicSquaresInside(vector<vector<int>>& grid) {
        int res = 0;
        int row = grid.size(), col = grid[0].size();

        for (int i = 0; i < row - 2; i++) {
            for (int j = 0; j < col - 2; j++) {
                if (isMagic(i, j, grid))
                    res++;
            }
        }

        return res;
    }
};
Leave a Comment