840. Magic Squares In Grid
Medium
Topics: Array, Hash Table, Math, Matrix
A 3 x 3 magic square is a3 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 a row x col grid of integers, how many 3 x 3 contiguous magic square subgrids are there?
Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up to 15.
Example 1:
while this one is not:
In total, there is only one magic square inside the given grid.
Example 2:
Constraints:
Solution:
We need to count how many 3x3 contiguous subgrids in the given grid form a magic square. A magic square is a 3x3 grid where all rows, columns, and both diagonals sum to the same value, and it contains the distinct numbers from 1 to 9.
To solve this problem, we can follow these steps:
Check if a Subgrid is Magic:
Iterate through the Grid:
Let's implement this solution in PHP: 840. Magic Squares In Grid
Explanation:
isMagic function:
- Extracts the 3x3 subgrid.
- Checks if all numbers are distinct and between 1 to 9.
- Verifies that the sums of the rows, columns, and diagonals are all 15.
numMagicSquaresInside function:
- Iterates over all possible 3x3 subgrids in the given grid.
- Counts how many of those subgrids are magic squares.
This code works efficiently within the constraints, counting all 3x3 magic square subgrids in the given grid.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Magic Squares In Grid. For more information, please follow other related articles on the PHP Chinese website!