zoukankan      html  css  js  c++  java
  • 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
                
                        
  • 相关阅读:
    Gin+Gorm小项目
    python实现监控信息收集
    Vue引入Stylus
    Go搭建一个Web服务器
    saltstack高效运维
    04-01 Django之模板层
    03-01 Django之视图层
    02-01 Django之路由层
    HTTP协议
    01-01 Web应用
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13308215.html
Copyright © 2011-2022 走看看