Skip to content

840. Magic Squares In Grid #293

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to count how many 3x3 contiguous subgrids in the given grid form a magic square. A magic square is a 3x3 grid where all rows, columns, and both diagonals sum to the same value, and it contains the distinct numbers from 1 to 9.

To solve this problem, we can follow these steps:

  1. Check if a Subgrid is Magic:

    • The subgrid must contain all distinct numbers from 1 to 9.
    • The sum of each row, column, and diagonal should be 15.
  2. Iterate through the Grid:

    • Since we need to check 3x3 subgrids, we will iterate from 0 to row-2 for rows and from 0 to col-2 for columns.
    • For each top-left corner of the 3x3 subgrid, extract the subgrid and check if it's a magic square.

Let's implement this s…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Aug 9, 2024
Maintainer Author

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Jan 23, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants