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 <= 101 <= grid[0].length <= 100 <= grid[i][j] <= 15
-----------------------------------------------------
It's a problem full of tricks.
First, we should demontrate the center of 3 x 3 magic square is 5.
Second, we could enumerate all other 8 nums, it will be clockwise or anticlockwise for "61834927", meanwhile, the corner will always be even number.

So the code is :
from typing import List
class Solution:
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
def is_magic(x,y):
nonlocal grid
lst = [grid[x+i//3][y+i%3] for i in [0,1,2,5,8,7,6,3]]
s = ''.join(str(item) for item in lst)
#一旦中间5确定,magic squre剩下8个数刚好是61834927循环,同时corner上一定是偶数
return lst[0]%2 == 0 and (s in "61834927"*2 or s in "61834927"[::-1]*2)
rows,cols,res = len(grid),len(grid[0]) if grid else 0,0
for i in range(rows-2):
for j in range(cols-2):
if (grid[i+1][j+1] == 5 and is_magic(i,j)):
res += 1
return res
s = Solution()
print(s.numMagicSquaresInside([[4,3,8,4],
[9,5,1,9],
[2,7,6,2]]))

探讨了如何在给定的二维网格中寻找并计数3x3魔法方格子网格的方法,魔法方格是指一个3x3的矩阵,其中包含从1到9的不同数字,每一行、每一列及两条对角线上的数字之和相等。
827

被折叠的 条评论
为什么被折叠?



