840. Magic Squares In Grid

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).

给一个矩阵,问有多少个3*3的子矩阵,满足每个格子是1-9里不同的数,然后行列对角线相加相等。

就是一道大模拟题

class Solution(object):
    def numMagicSquaresInside(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        n = len(grid)
        m = len(grid[0])
        
        def is_magic(a, b, c, d, e, f, g, h, i):
            flag = sorted([a, b, c, d, e, f, g, h, i]) == range(1, 10)
            flag &= (a + b + c == d + e + f == g + h + i == 
            a + d + g == b + e + h == c + f + i == a + e + i == c + e + g == 15)
            return flag
            
        ans = 0
        for i in range(n - 2):
            for j in range(m - 2):
                if is_magic(grid[i][j], grid[i][j + 1], grid[i][j + 2],
                           grid[i + 1][j], grid[i + 1][j + 1], grid[i + 1][j + 2],
                           grid[i + 2][j], grid[i + 2][j + 1], grid[i + 2][j + 2]):
                    ans += 1
                
        return ans
            
                    
原文地址:https://www.cnblogs.com/whatyouthink/p/13308215.html