# 840. Magic Squares In Grid Python题解

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

class Solution:
def numMagicSquaresInside(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res,n=0,len(grid)
isMag=['16729438','18349276','34927618','38167294','72943816','76183492','92761834','94381672']
for i in range(1,n-1):
for j in range(1,n-1):
if grid[i][j]==5:
tmp=''.join(map(str,[grid[i-1][j],grid[i-1][j+1],grid[i][j+1],grid[i+1][j+1],grid[i+1][j],\
grid[i+1][j-1],grid[i][j-1],grid[i-1][j-1]]))
res+=1 if tmp in isMag else 0
return res

10-20 619

11-09 38

03-18 146

01-01 29

05-27 1737

05-31 313

05-31 649

09-05 63

#### LeetCode-Magic Squares In Grid

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。