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.lengthn == grid[i].length1 <= m, n <= 501 <= grid[i][j] <= 106
Solutions
This function finds the largest magic square within a given grid, where a magic square is a square region where all rows, columns, and diagonals sum to the same value. The checkMagicSquare helper function verifies if a square at position (r, c) with size s is magical by computing the sums of each row, column, and both diagonals, then checking if they're all equal. The main algorithm iterates through every possible starting position in the grid and tries progressively larger square sizes from largest to smallest (using a break to avoid recalculating), keeping track of the maximum magic square size found and returning it.
/**
* @param {number[][]} grid
* @return {number}
*/
var largestMagicSquare = function(grid) {
const m = grid.length;
const n = grid[0].length;
let max = 0;
const checkMagicSquare = (r, c, s) => {
const rows = Array(s).fill(0);
const cols = Array(s).fill(0);
let diag1 = 0;
let diag2 = 0;
for (let row = 0; row < s; row++) {
for (let col = 0; col < s; col++) {
rows[row] += grid[row + r][col + c];
cols[col] += grid[row + r][col + c];
if (row === col) {
diag1 += grid[row + r][col + c];
}
if (row === s - 1 - col) {
diag2 += grid[row + r][col + c];
}
}
}
return diag1 === diag2 && rows.every(el => el === diag1) && cols.every(el => el === diag1);
};
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
for (let size = Math.min(m - row, n - col); size > 0; size--) {
if (size > max && checkMagicSquare(row, col, size)) {
max = size;
break;
}
}
}
}
return max;
};