Count Magic squares in a grid - GeeksforGeeks

17 Nov, 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++
Python3
C#
Javascript
// CPP program to count magic squares#include <bits/stdc++.h>using namespace std; const int R = 3;const int C = 4; // function to check is subgrid is Magic Squareint 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 subgridsint 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;          cout<<"ans = "<<ans<<endl;        }     // return total magic square    return ans;} // Driver programint 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 program to count magic squaresR = 3C = 4 # function to check is subgrid is Magic Squaredef 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 subgridsdef 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 Codeif __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
// C# program to count magic squaresusing System;using System.Collections.Generic; class GFg {    const int R = 3;    const int C = 4;     // function to check is subgrid is Magic Square    static int magic(int a, int b, int c, int d, int e,                     int f, int g, int h, int i)    {        HashSet<int> s1 = new HashSet<int>() {            a, b, c, d, e, f, g, h, i        };        HashSet<int> s2 = new HashSet<int>() {            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.SetEquals(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 1;        return 0;    }     // Function to count total Magic square subgrids    static int CountMagicSquare(int[, ] Grid)    {        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])                    != 0)                     ans += 1;            }         // return total magic square        return ans;    }     // Driver program    public static void Main()    {        int[, ] G = { { 4, 3, 8, 4 },                      { 9, 5, 1, 9 },                      { 2, 7, 6, 2 } };         // function call to print required answer        Console.WriteLine(CountMagicSquare(G));    }} // This code is contributed by ukasp.
<script> // JavaScript program to count magic squaresvar R = 3;var C = 4; function eqSet(as, bs) {    if (as.size !== bs.size) return false;    for (var a of as) if (!bs.has(a)) return false;    return true;} // function to check is subgrid is Magic Squarefunction magic(a, b, c, d, e, f, g, h, i){    var s1 = new Set([a, b, c, d, e, f, g, h, i]);    var s2 = new 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 (eqSet(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 subgridsfunction CountMagicSquare(Grid){    var ans = 0;     for (var i = 0; i < R - 2; i++)        for (var 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 programvar G = [[4, 3, 8, 4 ],                [ 9, 5, 1, 9 ],                [ 2, 7, 6, 2 ]];// function call to print required answerdocument.write( CountMagicSquare(G));  </script>
1
 
Time Complexity: O(R * C) 
rituraj_jain
shubham_singh
surinderdawra388
rrrtnx
ukasp
programming-puzzle
Mathematical
Matrix
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Print a given matrix in spiral form
Sudoku | Backtracking-7