840. Magic Squares In Grid #293
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count how many To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 840. Magic Squares In Grid <?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function isMagic($grid, $r, $c) {
// Extract the 3x3 grid
$nums = [
$grid[$r][$c], $grid[$r][$c+1], $grid[$r][$c+2],
$grid[$r+1][$c], $grid[$r+1][$c+1], $grid[$r+1][$c+2],
$grid[$r+2][$c], $grid[$r+2][$c+1], $grid[$r+2][$c+2]
];
// Check for distinct numbers from 1 to 9
$set = array_fill(1, 9, 0);
foreach ($nums as $num) {
if ($num < 1 || $num > 9 || $set[$num] == 1) {
return false;
}
$set[$num] = 1;
}
// Check the sums
return (
$grid[$r][$c] + $grid[$r][$c+1] + $grid[$r][$c+2] == 15 &&
$grid[$r+1][$c] + $grid[$r+1][$c+1] + $grid[$r+1][$c+2] == 15 &&
$grid[$r+2][$c] + $grid[$r+2][$c+1] + $grid[$r+2][$c+2] == 15 &&
$grid[$r][$c] + $grid[$r+1][$c] + $grid[$r+2][$c] == 15 &&
$grid[$r][$c+1] + $grid[$r+1][$c+1] + $grid[$r+2][$c+1] == 15 &&
$grid[$r][$c+2] + $grid[$r+1][$c+2] + $grid[$r+2][$c+2] == 15 &&
$grid[$r][$c] + $grid[$r+1][$c+1] + $grid[$r+2][$c+2] == 15 &&
$grid[$r][$c+2] + $grid[$r+1][$c+1] + $grid[$r+2][$c] == 15
);
}
/**
* @param $grid
* @param $r
* @param $c
* @return bool
*/
function numMagicSquaresInside($grid) {
$rows = count($grid);
$cols = count($grid[0]);
$count = 0;
for ($i = 0; $i <= $rows - 3; $i++) {
for ($j = 0; $j <= $cols - 3; $j++) {
if (isMagic($grid, $i, $j)) {
$count++;
}
}
}
return $count;
}
// Example usage:
$grid1 = [
[4, 3, 8, 4],
[9, 5, 1, 9],
[2, 7, 6, 2]
];
echo numMagicSquaresInside($grid1); // Output: 1
$grid2 = [
[18]
];
echo numMagicSquaresInside($grid2); // Output: 0
?> Explanation:
This code works efficiently within the constraints, counting all |
Beta Was this translation helpful? Give feedback.
We need to count how many
3x3
contiguous subgrids in the given grid form a magic square. A magic square is a3x3
grid where all rows, columns, and both diagonals sum to the same value, and it contains the distinct numbers from1
to9
.To solve this problem, we can follow these steps:
Check if a Subgrid is Magic:
1
to9
.15
.Iterate through the Grid:
3x3
subgrids, we will iterate from0
torow-2
for rows and from0
tocol-2
for columns.3x3
subgrid, extract the subgrid and check if it's a magic square.Let's implement this s…