Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.6 kB
0
Indexable
Never
class Solution {
public:
    int numMagicSquaresInside(vector<vector<int>>& grid) {
        int ans = 0;
        int row = grid.size(), col = grid[0].size();
        if (row < 3 || col < 3) return 0;
        for (int i=0; i<=row-3; ++i) {
            for (int j=0; j<=col-3; ++j) {
                bool arr[16];
                bool pass = true;
                for (int i=0; i<=15; ++i) arr[i] = false;
                for (int r=i; r<i+3; ++r) {
                    int rowSum = 0;
                    for (int c=j; c<j+3; ++c) {
                        rowSum += grid[r][c];
                    }
                    if (rowSum != 15) {
                        pass = false;
                        break;
                    }
                }
                for (int c=j; c<j+3; ++c) {
                    int colSum = 0;
                    for (int r=i; r<i+3; ++r) {
                        colSum += grid[r][c];
                    }
                    if (colSum != 15) {
                        pass = false;
                        break;
                    }
                }
                for (int r=i; r<i+3; ++r) {
                    for (int c=j; c<j+3; ++c) {
                        arr[grid[r][c]] = true;
                    }
                }
                for (int k=1; k<=9; ++k) {
                    if (!arr[k]) pass = false;
                }
                if (grid[i][j] + grid[i+1][j+1] + grid[i+2][j+2] != 15) pass = false;
                if (grid[i][j+2] + grid[i+1][j+1] + grid[i+2][j] != 15) pass = false;
                if (pass) ans ++;
            }
        }
        return ans;
    }
};
Leave a Comment