Skip to content
Related Articles
Count Magic squares in a grid
• Difficulty Level : Medium
• Last Updated : 21 May, 2021

Given an Grid of integers. The task is to find total numbers of 3 x 3 (contiguous) Magic Square subgrids in the given grid. A Magic square is a 3 x 3 grid filled with all distinct numbers from 1 to 9 such that each row, column, and both diagonals have equal sum.
Examples:

Input: G = { { 4, 3, 8, 4 }, { 9, 5, 1, 9 }, { 2, 7, 6, 2 } }
Output: 1
Explanation: The following subgrid is a 3 x 3 magic square: [ 4 3 8, 9 5 1, 2 7 6 ]
Input : G = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 10, 11, 12, 13, 14 }, { 15, 16, 17, 18, 19 } }
Output : 0

Approach: Let us check every 3 x 3 subgrid individually. For each grid, all numbers must be unique and between (1 and 9) also every rows, columns, and both diagonals must have the equal sum.
Also notice the fact that a subgrid is a Magic Square if its middle element is 5. Because adding the 12 values from the four lines that crosses the center, add up to 60, but they also add up to the entire grid (45), plus 3 times the middle value. This implies the middle value is 5. Hence we can check this condition which help us skip over various subgrids.
You can learn more about Magic_square here or here.
The procedure to check for a subgrid to be a Magic Square is as follows:

• The middle element must be 5.
• The sum of the grid must be 45, and contains all distinct values from 1 to 9.
• Each horizontal(row) and vertical(column) must add up to 15.
• Both of the diagonal lines must also sum to 15.

Below is the implementation of above approach:

## C++

 `// CPP program to count magic squares``#include ``using` `namespace` `std;` `const` `int` `R = 3;``const` `int` `C = 4;` `// function to check is subgrid is Magic Square``int` `magic(``int` `a, ``int` `b, ``int` `c, ``int` `d, ``int` `e,``                ``int` `f, ``int` `g, ``int` `h, ``int` `i)``{``    ``set<``int``> s1 = { a, b, c, d, e, f, g, h, i },``             ``s2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };` `    ``// Elements of grid must contain all numbers from 1 to``    ``// 9, sum of all rows, columns and diagonals must be``    ``// same, i.e., 15.``    ``if` `(s1 == s2 && (a + b + c) == 15 && (d + e + f) == 15 &&``       ``(g + h + i) == 15 && (a + d + g) == 15 &&                    ``       ``(b + e + h) == 15 && (c + f + i) == 15 &&``       ``(a + e + i) == 15 && (c + e + g) == 15)``       ``return` `true``;``    ``return` `false``;   ``}` `// Function to count total Magic square subgrids``int` `CountMagicSquare(``int` `Grid[R][C])``{``    ``int` `ans = 0;` `    ``for` `(``int` `i = 0; i < R - 2; i++)``        ``for` `(``int` `j = 0; j < C - 2; j++) {` `            ``// if condition true skip check``            ``if` `(Grid[i + 1][j + 1] != 5)``                ``continue``;` `            ``// check for magic square subgrid``            ``if` `(magic(Grid[i][j], Grid[i][j + 1],``                ``Grid[i][j + 2], Grid[i + 1][j],``                ``Grid[i + 1][j + 1], Grid[i + 1][j + 2],``                ``Grid[i + 2][j], Grid[i + 2][j + 1],``                ``Grid[i + 2][j + 2]))` `                ``ans += 1;``        ``}` `    ``// return total magic square``    ``return` `ans;``}` `// Driver program``int` `main()``{``    ``int` `G[R][C] = { { 4, 3, 8, 4 },``                    ``{ 9, 5, 1, 9 },``                    ``{ 2, 7, 6, 2 } };` `    ``// function call to print required answer``    ``cout << CountMagicSquare(G);` `    ``return` `0;``}` `// This code is written by Sanjit_Prasad`

## Python3

 `# Python3 program to count magic squares``R ``=` `3``C ``=` `4` `# function to check is subgrid is Magic Square``def` `magic(a, b, c, d, e, f, g, h, i):` `    ``s1 ``=` `set``([a, b, c, d, e, f, g, h, i])``    ``s2 ``=` `set``([``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8``, ``9``])` `    ``# Elements of grid must contain all numbers``    ``# from 1 to 9, sum of all rows, columns and``    ``# diagonals must be same, i.e., 15.``    ``if` `(s1 ``=``=` `s2 ``and` `(a ``+` `b ``+` `c) ``=``=` `15` `and``       ``(d ``+` `e ``+` `f) ``=``=` `15` `and` `(g ``+` `h ``+` `i) ``=``=` `15` `and``       ``(a ``+` `d ``+` `g) ``=``=` `15` `and` `(b ``+` `e ``+` `h) ``=``=` `15` `and``       ``(c ``+` `f ``+` `i) ``=``=` `15` `and` `(a ``+` `e ``+` `i) ``=``=` `15` `and``       ``(c ``+` `e ``+` `g) ``=``=` `15``):``        ``return` `True``        ` `    ``return` `false    ` `# Function to count total Magic square subgrids``def` `CountMagicSquare(Grid):` `    ``ans ``=` `0` `    ``for` `i ``in` `range``(``0``, R ``-` `2``):``        ``for` `j ``in` `range``(``0``, C ``-` `2``):` `            ``# if condition true skip check``            ``if` `Grid[i ``+` `1``][j ``+` `1``] !``=` `5``:``                ``continue` `            ``# check for magic square subgrid``            ``if` `(magic(Grid[i][j], Grid[i][j ``+` `1``],``                  ``Grid[i][j ``+` `2``], Grid[i ``+` `1``][j],``                  ``Grid[i ``+` `1``][j ``+` `1``], Grid[i ``+` `1``][j ``+` `2``],``                  ``Grid[i ``+` `2``][j], Grid[i ``+` `2``][j ``+` `1``],``                  ``Grid[i ``+` `2``][j ``+` `2``]) ``=``=` `True``):` `                ``ans ``+``=` `1` `    ``# return total magic square``    ``return` `ans` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``G ``=` `[[``4``, ``3``, ``8``, ``4``],``         ``[``9``, ``5``, ``1``, ``9``],``         ``[``2``, ``7``, ``6``, ``2``]]` `    ``# Function call to print required answer``    ``print``(CountMagicSquare(G))``    ` `# This code is contributed by Rituraj Jain`
Output:
`1`

Time Complexity: O(R * C)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up