Magic Squares in Grid in C++



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}, {-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][0]][j+offset[k][1]];
            }
            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
Updated on: 2020-07-04T10:12:01+05:30

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements