1. 程式人生 > 實用技巧 >840. Magic Squares In Grid

840. Magic Squares In Grid

A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbersfrom 1 to 9such that each row, column, and both diagonals all have the same sum.

Given angridof 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