Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Math
Magic Squares In Grid

Count how many 3×3 subgrids of a matrix form a magic square.

Acceptance 100%
Problem Statement

Given a 2D integer grid, count how many 3×3 subgrids are magic squares.

A 3×3 grid is a magic square if it contains each number from 1 to 9 exactly once and every row, column, and both diagonals have the same sum.

Input Format

  • An integer matrix grid with m rows and n columns.
  • You need to examine every 3×3 subgrid of grid.

Output Format

Return the number of 3×3 subgrids that are magic squares.

Constraints

  • 1 <= m, n <= 10 is typical for this problem family.
  • All values are integers.
  • Only 3×3 subgrids are considered.

Note: Exact platform constraints may vary; this is a prep-oriented restatement.

Examples
Sample cases returned by the problem API.

Example 1

Input

grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]

Output

1

Explanation

The 3×3 subgrid starting at the top-left is a magic square: it contains 1 through 9 once each, and every row, column, and diagonal sums to 15.

Example 2

Input

grid = [[8]]

Output

0

Explanation

A single cell cannot form a 3×3 magic square.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.