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 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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值