Problem Statement:
You are given a matrix, you need to check if the matrix is a Magic Square or not.
A matrix is a magic square of n * n, satisfies below conditions:
1. It has distinct elements from 1 to n^2.
2.The sum of any row, column or diagonal is equal to the same number.
Example:
Input:
2 7 6
9 5 1
4 3 8
Output:
Yes.
Sum of each row and column and diagonal is 15
Solution Explanation:
For the solution calculate below steps:
1. Find the sum of prime diagonal and secondary diagonal
2. Find the sum of each row and column.
If all the sum are same, then it is a magic matrix.
Time Complexity: O(1)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
bool solution(int mat[3][3])
{
int n = 3;
int i = 0;
int j = 0;
int sumd1 = 0;
int sumd2 = 0;
for (i = 0; i < n; i++)
{
sumd1 += mat[i][i];
sumd2 += mat[i][n-1-i];
}
if(sumd1!=sumd2)
return false;
for (i = 0; i < n; i++) {
int rowSum = 0, colSum = 0;
for (j = 0; j < n; j++)
{
rowSum += mat[i][j];
colSum += mat[j][i];
}
if (rowSum != colSum || colSum != sumd1)
return false;
}
return true;
}
int main()
{
int mat[3][3] = {{ 2, 7, 6 },
{ 9, 5, 1 },
{ 4, 3, 8 }};
if (solution(mat))
cout << "Magic Square";
else
cout << "Not a magic Square";
return 0;
}
Output
Magic Square