码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 840. Magic Squares In Grid_Easy

时间:2018-08-28 13:11:18      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:input   lan   inpu   ids   center   sorted   sum   sam   ide   

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

In 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

 

[LeetCode] 840. Magic Squares In Grid_Easy

标签:input   lan   inpu   ids   center   sorted   sum   sam   ide   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9547361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!