Leetcode 1895. Largest Magic Square

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1895. Largest Magic Square相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Largest Magic Square

2. Solution

**解析:**根据幻方定义,分别检查主对角线、副对角线、各行、各列的和是否相等,按阶次从大到小依次检查,碰到满足条件的返回阶。

  • Version 1
class Solution:
    def largestMagicSquare(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        size = min(m, n)
        for k in range(size, 0, -1):
            for i in range(m-k+1):
                for j in range(n-k+1):
                    if self.check(grid, i, j, k):
                        return k


    def check(self, grid, x, y, k):
        main_diagonal = 0
        secondary_diagonal = 0
        for i in range(k):
            main_diagonal += grid[x+i][y+i]
            secondary_diagonal += grid[x+i][y+k-i-1]
        if main_diagonal != secondary_diagonal:
            return False

        for i in range(k):
            row = sum(grid[x+i][y:y+k])
            if row != main_diagonal:
                return False
            column = sum([grid[x+j][y+i] for j in range(k)])
            if column != main_diagonal:
                return False
        return True

Reference

  1. https://leetcode.com/problems/largest-magic-square/

以上是关于Leetcode 1895. Largest Magic Square的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]184. Largest Number/[Leetcode]179. Largest Number

#Leetcode# 179. Largest Number

LeetCode Largest Divisible Subset

Leetcode410. Split Array Largest Sum

leetcode 179 Largest Number

LeetCode(179) Largest Number