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 <= grid.length <= 10
1 <= grid[0].length <= 10
0 <= grid[i][j] <= 15
你需要做的就是判断九宫格内
1. 是否是1-9 9个不同的数组成
2. 3横,三竖,2斜的和是否是15(中间的数必须是5)
int numMagicSquaresInside(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int result = 0;
//cout<<grid[1][1]<<grid[1][2]<<endl;
for (int i = 1 ; i < m - 1 ;i++)
{
for(int j = 1 ; j < n - 1 ;j++)
{
int flag = 0;
int a[9] ={0};
//判断这9个数是否是1-9 这9个不同数组成
for(int p = i-1 ; p<=i+1;p++)
{
for(int q = j-1;q<=j+1;q++)
{
if (grid[p][q]<=9 && grid[p][q]>=1)
{
a[grid[p][q]-1] = 1;
}
}
}
//是的,flag = 0,不是flag =1
for (int p = 0;p<9;p++)
{
if(a[p] == 0)
{
flag = 1;
}
}
//满足和为15 中间的数必须是5
if(grid[i][j] != 5 )
{
continue;
}
else if(flag == 1)
continue;
else if(grid[i][j+1] + grid[i][j-1] != 10 ||grid[i+1][j] + grid[i-1][j] != 10 ||grid[i+1][j+1] + grid[i-1][j-1] != 10 ||grid[i+1][j-1] + grid[i-1][j+1] != 10 || grid[i-1][j-1] +grid[i-1][j]+grid[i-1][j+1]!= 15||grid[i+1][j-1] +grid[i+1][j]+grid[i+1][j+1]!= 15||grid[i-1][j-1] +grid[i][j-1]+grid[i+1][j-1]!= 15 || grid[i-1][j+1] +grid[i][j+1]+grid[i+1][j+1]!= 15)
{
continue;
}else
{
result++;
}
}
}
return result;
}