Magic Squares In Grid

A 3 x 3 magic square is a 3 x 3 grid filled with the distinct numbers 1 to 9 such that every row, every column and both diagonals have the same sum. Given a row x col grid of integers, count how many contiguous 3 x 3 subgrids are magic squares. The grid itself may contain numbers up to 15.

30:00

Magic Squares In Grid
medium
Free written solution
Topics
Companies

A 3 x 3 magic square is a 3 x 3 grid filled with the distinct numbers 1 to 9 such that every row, every column and both diagonals have the same sum. Given a row x col grid of integers, count how many contiguous 3 x 3 subgrids are magic squares. The grid itself may contain numbers up to 15.

Example 1:
Input: {"grid":[[4,3,8,4],[9,5,1,9],[2,7,6,2]]}
Output: 1
Constraints:
  • row=grid.length\text{row} = \text{grid.length}

  • col=grid[i].length\text{col} = \text{grid}[i]\text{.length}

  • 1≤row,col≤101 \leq \text{row}, \text{col} \leq 10

  • 0≤grid[i][j]≤150 \leq \text{grid}[i][j] \leq 15

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[4,3,8,4],[9,5,1,9],[2,7,6,2]]}

A 3 x 4 grid has 2 possible 3 x 3 windows. Slide one over every position.

grid, sliding 3 x 3 window

4
3
8
4
9
5
1
9
2
7
6
2

window check

No window under inspection.

count = 0

Variables
VariableValue
rows3
cols4
DepthFunction Call
Stack empty
0/8