Forming a Magic Square

We define a magic square to be an nXn matrix of distinct positive integers from 1 to n^2 where the sum of any row, column, or diagonal of length n is always equal to the same number: the magic constant.
You will be given a 3X3 matrix s  of integers in the inclusive range [1,9]. We can convert any digit a to any other digit b in the range [1,9] at cost of abs(a-b). Given s, convert it into a magic square at a minimal cost. Find this cost.
Note: The resulting magic square must contain distinct integers in the inclusive range [1,9].

Example:

Input:  brr[3][3]={{5,3,4},{1,5,8},{6,4,2}}
Output: 7

Approach

C++

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int brr[3][3] = {{534}, {158}, {642}};

    int arr[8][3][3] = {{{816}, {357}, {492}},
                        {{618}, {753}, {294}},
                        {{492}, {357}, {816}},
                        {{294}, {753}, {618}},
                        {{834}, {159}, {672}},
                        {{438}, {951}, {276}},
                        {{672}, {159}, {834}},
                        {{276}, {951}, {438}}};
    int res = INT_MAX;
    for (int k = 0k < 8k++)
    {
        int ans = 0;
        for (int i = 0i < 3i++)
        {
            for (int j = 0j < 3j++)
                ans += abs(arr[k][i][j] - brr[i][j]);
        }
        res = min(resans);
    }
    cout << res << "\n";
    return 0;
}



No comments:

Post a Comment