# Magic Squares In Grid in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have a grid we have to find the number of magic square sub-grid into that grid. A magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

So, if the input is like

 4 3 8 4 9 5 1 9 2 7 6 2

then the output will be 1, as the magic square is

 4 3 8 9 5 1 2 7 6

To solve this, we will follow these steps −

• Define one set with values: [816357492, 834159672, 618753294, 672159834,492357816, 438951276, 294753618, 276951438]
• Define an array offset of size: 9 x 2 := {{-2,-2},{-2,-1},{-2,0},{-1,-2},{-1,-1},{-1,0},{0,-2},{0,-1},{0,0}}
• ans := 0
• for initialize i := 2, when i < grid row count, update (increase i by 1), do −
• for initialize j := 2, when j < grid row count, update (increase j by 1), do −
• sum := 0
• for initialize k := 0, when k < 9, update (increase k by 1), do −
• sum := sum * 10
• sum := sum + grid[i + offset[k, 0], j + offset[k, 1]]
• ans := ans + occurrence of sum in s
• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numMagicSquaresInside(vector<vector<int>>& grid) {
const unordered_set<int> s{816357492, 834159672, 618753294,
672159834,492357816, 438951276, 294753618,276951438};
const int offset[] = {{-2, -2}, {-2, -1}, {-2, 0},{-1, -2}, {-1, -1}, {-1, 0},
{ 0, -2}, { 0, -1}, { 0, 0}};
int ans = 0;
for(int i = 2; i< grid.size(); i++)
{
for(int j = 2; j<grid.size(); j++)
{
int sum = 0;
for(int k = 0; k<9; k++)
{
sum *= 10;
sum += grid[i + offset[k]][j+offset[k]];
}
ans += s.count(sum);
}
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{4,3,8,4},{9,5,1,9},{2,7,6,2}};
cout << (ob.numMagicSquaresInside(v));
}

## Input

{{4,3,8,4},{9,5,1,9},{2,7,6,2}}

## Output

1