Magic Squares In Grid

Medium Topics Company Tags

Count the contiguous 3 x 3 subgrids of grid that contain each integer from 1 through 9 exactly once and have the same sum in all three rows, all three columns, and both diagonals. Every possible position is checked separately, and qualifying squares may overlap. Entries outside 1 through 9 are allowed in the input but cannot belong to a qualifying square.

Example 1:

Magic Squares In Grid, example 1: illustration of the example

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

Output: 1

Explanation: The grid uses every number 1 through 9 exactly once. Each row, each column, and both diagonals sum to 15, so its only 3 by 3 window qualifies.

Example 2:

Magic Squares In Grid, example 2: illustration of the example

Input: grid = [[5,5,5],[5,5,5],[5,5,5]]

Output: 0

Explanation: Every line sums to 15, but the entries repeat 5 instead of using the numbers 1 through 9 once each. It is not a magic square.

Example 3:

Magic Squares In Grid, example 3: illustration of the example

Input: grid = [[1,2,3]]

Output: 0

Explanation: The grid has only one row, so it contains no 3 by 3 window.

Constraints:

  • 1 <= grid.length <= 10
  • Every row has the same length, between 1 and 10.
  • 0 <= grid[i][j] <= 15


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.