题目
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
解题思路
首先我们每次从中提取出一个33的方阵。那么对于一个nn的方阵,一共可以提取出w-2*h-2的不同方阵。于是,对每个方阵判断是否属于神奇方阵。
神奇方阵的特点是:
- 对角线和相同。
- 总和=1-9相加即45.
- 各行和相同。
- 各列和相同。
- 有一个隐藏必备条件,就是中间位置必为5,如果不为5,那么直接下一个。
观察发现:
可以构造一个检测表:
check = '67294381' * 2
check += check[::-1]
如果从属于该检测序列的子串,那么即是一个神奇方阵。
然后遍历一共w-2*h-2的方阵,构造字符串判断其是否属于检测序列。
优秀代码
class Solution:
def numMagicSquaresInside(self, grid: 'List[List[int]]') -> 'int':
check = '67294381' * 2
check += check[::-1]
order = [(0,0),(0,1),(0,2),(1,2),(2,2),(2,1),(2,0),(1,0)]
def isMagic(i, j):
if grid[i + 1][j + 1] != 5:
return False
return ''.join(str(grid[x + i][y + j]) for x, y in order) in check
return sum(1 for i in range(len(grid) - 2) for j in range(len(grid[i]) - 2) if isMagic(i, j))