题目:
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
解释:
magic square 一定要是以5
为中心
只需要判断四条边和两条斜边的值是否是15即可,用or 判断
python代码:
class Solution:
def numMagicSquaresInside(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
self.m,self.n=len(grid),len(grid[0])
self.grid=grid
def isMagic(i,j):
if self.grid[i+1][j+1]!=5:
return False
for _i in range(i,i+3):
for _j in range(j,j+3):
if self.grid[_i][_j] not in range(1,10):
return False
if self.grid[i][j]+self.grid[i][j+1]+self.grid[i][j+2]!=15 or self.grid[i+2][j]+self.grid[i+2][j+1]+self.grid[i+2][j+2]!=15 or self.grid[i][j]+self.grid[i+1][j]+self.grid[i+2][j]!=15 or self.grid[i][j+2]+self.grid[i+1][j+2]+self.grid[i+2][j+2]!=15 or self.grid[i][j]+self.grid[i+1][j+1]+self.grid[i+2][j+2]!=15 or self.grid[i][j+2]+self.grid[i+1][j+1]+self.grid[i+2][j]!=15:
return False
return True
count=0
for i in range(self.m-2):
for j in range(self.n-2):
if isMagic(i,j):
count+=1
return count
c++代码:
class Solution {
public:
int numMagicSquaresInside(vector<vector<int>>& grid) {
int count=0;
int m=grid.size();
int n=grid[0].size();
for (int i=0;i<m-2;i++)
{
for(int j=0;j<n-2;j++)
{
if(isMagic(grid,i,j))
count++;
}
}
return count;
}
bool isMagic(vector<vector<int>> &grid,int i,int j)
{
if (grid[i+1][j+1]!=5)
return false;
for(int _i=i;_i<i+3;_i++)
{
for(int _j=j;_j<j+3;_j++)
{
if ((grid[_i][_j]>9) || (grid[_i][_j]<1))
return false;
}
}
if(grid[i][j]+grid[i][j+1]+grid[i][j+2]!=15 || grid[i+2][j]+grid[i+2][j+1]+grid[i+2][j+2]!=15 || grid[i][j]+grid[i+1][j]+grid[i+2][j]!=15 || grid[i][j+2]+grid[i+1][j+2]+grid[i+2][j+2]!=15 || grid[i][j]+grid[i+1][j+1]+grid[i+2][j+2]!=15 || grid[i][j+2]+grid[i+1][j+1]+grid[i+2][j]!=15)
return false;
return true;
}
};
总结: