博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 840. Magic Squares In Grid_Easy
阅读量:4608 次
发布时间:2019-06-09

本文共 1691 字,大约阅读时间需要 5 分钟。

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: 1Explanation: The following subgrid is a 3 x 3 magic square:438951276while this one is not:384519762In 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

 

思路就是依次扫, 只是利用

Here I just want share two observatons with this 1-9 condition:

 

Assume a magic square:

a1,a2,a3
a4,a5,a6
a7,a8,a9

 

a2 + a5 + a8 = 15

a4 + a5 + a6 = 15
a1 + a5 + a9 = 15
a3 + a5 + a7 = 15

 

Accumulate all, then we have:

sum(ai) + 3 * a5 = 60
3 * a5 = 15
a5 = 5

 

The center of magic square must be 5.  这个条件来去减少一些判断.

 

Code:

class Solution:    def numMagicSquaresInside(self, grid):        ans, lrc = 0, [len(grid), len(grid[0])]        def checkMagic(a,b, c, d, e, f, g ,h, i):            return (sorted([a,b,c,d,e,f,g,h,i]) == [i for i in range(1,10)] and                    (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))        for i in range(1, lrc[0]-1):            for j in range(1, lrc[1]-1):                if grid[i][j] == 5 and checkMagic(grid[i-1][j-1], grid[i-1][j], grid[i-1][j+1],                             grid[i][j-1], grid[i][j], grid[i][j+1],                             grid[i+1][j-1], grid[i+1][j], grid[i+1][j+1]):                    ans += 1        return ans

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9547361.html

你可能感兴趣的文章
netty与MQ使用心得
查看>>
关于dl dt dd 文字过长换行在移动端显示对齐的探讨总结
查看>>
swoolefy PHP的异步、并行、高性能网络通信引擎内置了Http/WebSocket服务器端/客户端...
查看>>
Python学习笔记
查看>>
unshift()与shift()
查看>>
使用 NPOI 、aspose实现execl模板公式计算
查看>>
行为型模式:中介者模式
查看>>
How to Notify Command to evaluate in mvvmlight
查看>>
33. Search in Rotated Sorted Array
查看>>
461. Hamming Distance
查看>>
Python垃圾回收机制详解
查看>>
jquery 编程的最佳实践
查看>>
MeetMe
查看>>
IP报文格式及各字段意义
查看>>
(转载)rabbitmq与springboot的安装与集成
查看>>
C2. Power Transmission (Hard Edition)(线段相交)
查看>>
STM32F0使用LL库实现SHT70通讯
查看>>
Atitit. Xss 漏洞的原理and应用xss木马
查看>>
MySQL源码 数据结构array
查看>>
(文件过多时)删除目录下全部文件
查看>>