Magic Squares In Grid - Problem
Magic Squares in Grid
A 3×3 magic square is a fascinating mathematical construct where a 3×3 grid is filled with distinct numbers from 1 to 9 such that:
• Each row sums to the same value
• Each column sums to the same value
• Both diagonals sum to the same value
For example:
Each row, column, and diagonal sums to 15! 🎯
Given a
A 3×3 magic square is a fascinating mathematical construct where a 3×3 grid is filled with distinct numbers from 1 to 9 such that:
• Each row sums to the same value
• Each column sums to the same value
• Both diagonals sum to the same value
For example:
2 7 6
9 5 1
4 3 8Each row, column, and diagonal sums to 15! 🎯
Given a
row × col grid of integers, your task is to count how many 3×3 subgrids within this larger grid are valid magic squares. Note that while magic squares can only contain numbers 1-9, the input grid may contain numbers up to 15. Input & Output
example_1.py — Basic Magic Square
$
Input:
grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
›
Output:
1
💡 Note:
The 3×3 subgrid starting at position (0,0) contains numbers 1-9 exactly once, and all rows, columns, and diagonals sum to 15
example_2.py — No Magic Squares
$
Input:
grid = [[8]]
›
Output:
0
💡 Note:
The grid is too small to contain any 3×3 subgrids
example_3.py — Multiple Candidates
$
Input:
grid = [[5,5,5],[5,5,5],[5,5,5]]
›
Output:
0
💡 Note:
While all sums equal 15, the numbers are not distinct (all 5s), so this is not a valid magic square
Constraints
- 1 ≤ grid.length, grid[i].length ≤ 10
- 0 ≤ grid[i][j] ≤ 15
- Magic squares must contain numbers 1-9 exactly once
- All rows, columns, and diagonals must sum to 15
Visualization
Tap to expand
Understanding the Visualization
1
Position Scanner
Move the 3×3 scanning window to each possible position in the grid
2
Number Validation
Check if the current 3×3 area contains numbers 1-9 exactly once
3
Sum Verification
Verify all rows, columns, and diagonals sum to the magic number 15
4
Count Magic Squares
Increment counter for each valid magic square found
Key Takeaway
🎯 Key Insight: Magic squares have fixed properties (numbers 1-9, sum=15) that make validation efficient with just basic checking!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code