首页 技术 正文
技术 2022年11月10日
0 收藏 412 点赞 4,284 浏览 1169 个字

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
276while this one is not:
384
519
762In 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
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,493
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297