- Link: 840. Magic Squares In Grid - Medium
- Track: NeetCode150
Question
Restate the problem
- Given a rows x cols grid of integers
- Count how many 3 x 3 subgrids are magic squares
- A magic square means:
- It contains all numbers from 1 to 9 exactly once
- Every row, every column, and both diagonals have the same sum
Edge Case
- Grid smaller than
3 x 3→ return0 - A
3 x 3subgrid contains duplicate numbers → not a magic square
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Brute force (check every 3 x 3 box) |
Method 1 - Brute force
Key idea:
- For any valid
3 x 3magic square using digits1..9exactly once, the center must be5, enabling early pruning.- 对于任何一个由
1..9恰好组成的合法3 x 3幻方,中心位置必须是5,因此可以提前进行剪枝。
Approach
- Since a magic square must be exactly
3 x 3, scan every possible center cell - For each center
(r, c), collect the surrounding3 x 3values - Check whether:
- The subgrid contains every number from
1to9 - All 3 rows have the same sum
- All 3 columns have the same sum
- Both diagonals have the same sum
- The subgrid contains every number from
- If all conditions are true, count it as one magic square
Complexity
- Time Complexity:
- Space Complexity:
Code
class Solution:
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
def magic_square(row, col):
val = []
for r in [row - 1, row, row + 1]:
for c in [col - 1, col, col + 1]:
val.append(grid[r][c])
for idx in range(1, 10):
if idx not in val:
return False
total = sum(val[:3])
# check row
for idx in [0, 3, 6]:
if sum(val[idx: idx+3]) != total:
return False
# check col
for idx in [0, 1, 2]:
if (val[idx] + val[idx+3] + val[idx+6]) != total:
return False
# check diagonals
if (val[0] + val[4] + val[8]) != total:
return False
if (val[2] + val[4] + val[6]) != total:
return False
return True
count = 0
for r in range(1, rows - 1):
for c in range(1, cols - 1):
if grid[r][c] != 5:
continue
if magic_square(r, c):
count += 1
return countMistake
- A valid
3 x 3magic square using1..9must have center5