您的位置:首页 > 娱乐 > 八卦 > 安徽建筑工程信息网查询_网页升级未成年请自觉离开_seo网站优化收藏_培训学校资质办理条件

安徽建筑工程信息网查询_网页升级未成年请自觉离开_seo网站优化收藏_培训学校资质办理条件

2025/2/24 4:30:55 来源:https://blog.csdn.net/sinat_41679123/article/details/144656431  浏览:    关键词:安徽建筑工程信息网查询_网页升级未成年请自觉离开_seo网站优化收藏_培训学校资质办理条件
安徽建筑工程信息网查询_网页升级未成年请自觉离开_seo网站优化收藏_培训学校资质办理条件

Description

A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.

Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.

Example 1:
在这里插入图片描述

Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
Output: 3
Explanation: The largest magic square has a size of 3.
Every row sum, column sum, and diagonal sum of this magic square is equal to 12.
- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12
- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12
- Diagonal sums: 5+4+3 = 6+4+2 = 12

Example 2:

在这里插入图片描述

Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]
Output: 2

Constraints:

m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 10^6

Solution

Simulation, use a helper function to see if the row sums, column sums and diagonal sums are the same.

Time complexity: o ( m ∗ n ∗ n ) o(m*n*n) o(mnn)
Space complexity: o ( m ∗ n ) o(m*n) o(mn)

Code

class Solution:def largestMagicSquare(self, grid: List[List[int]]) -> int:def is_magic_square(x: int, y: int, size: int) -> bool:row_sums = [sum(grid[row][y: y + size]) for row in range(x, x + size)]col_sums = []for col in range(y, y + size):col_sums.append(0)for row in range(x, x + size):col_sums[-1] += grid[row][col]diag_sums = [0, 0]for row in range(x, x + size):diag_sums[0] += grid[row][row - (x - y)]diag_sums[1] += grid[row][x + y + size - row - 1]return all(item == row_sums[0] for item in row_sums + col_sums + diag_sums)res = 1m, n = len(grid), len(grid[0])for i in range(m):for j in range(n):for size in range(2, 1 + min(m - i, n - j)):if is_magic_square(i, j, size):res = max(res, size)return res

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com