Monday, August 3, 2020

840. Magic Squares In Grid ---------E

Q:

A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

Given an grid of integers, how many 3 x 3 "magic square" subgrids are there?  (Each subgrid is contiguous).

 

Example 1:

Input: [[4,3,8,4],
        [9,5,1,9],
        [2,7,6,2]]
Output: 1
Explanation: 
The following subgrid is a 3 x 3 magic square:
438
951
276

while this one is not:
384
519
762

In total, there is only one magic square inside the given grid.

Note:

  1. 1 <= grid.length <= 10
  2. 1 <= grid[0].length <= 10
  3. 0 <= grid[i][j] <= 15
A:
哎,一开始,题意理解错误。  TNND。 没有看懂题目就乱做。

class Solution {
public:
    int numMagicSquaresInside(vector<vector<int>>& grid) {
        int res = 0;
        for(int i =1;i+1<grid.size();++i)
            for(int j = 1;j+1<grid[0].size();++j)
                res += isMagic(grid,i,j)? 1:0;
        return res;
    }
private:
    bool isMagic(vector<vector<int>>& grid, int a, int b){
        vector<bool> V(9,false);
        for(int i =a-1;i<=a+1;++i)
            for(int j =b-1; j<=b+1;++j)
            {
                int val = grid[i][j];
                if(val <=0 || val > 9 || V[val-1])
                    return false;
                V[val-1]=true;
            }
        
        int sum = grid[a-1][b-1]+ grid[a][b]+ grid[a+1][b+1] ;
        for(int i =a-1;i<= a+1;++i){
            if(sum != grid[i][b-1]+ grid[i][b]+ grid[i][b+1] )
                return false;
        }
        for(int j =b-1;j<= b+1;++j){
            if(sum != grid[a-1][j]+ grid[a][j]+ grid[a+1][j] )
                return false;
        }        
        return sum ==grid[a-1][b+1]+ grid[a][b]+ grid[a+1][b-1];
    }
};



No comments:

Post a Comment