< Back to forum

what will be the approach to this problem https://www.hackerrank.com/challenges/magic-square-forming/problem

Enter your answer details below:


Enter your comment details below:


1 Answer(s)


method 1 :)

to solve this problem you have to generate all the possible matrix of size 3x3 which is a possible answer to the question. from all the 3x3 matrix with the distinct element from the range [1:9] (which is 9!), only 8 is satisfied with our requirement. to generate these 8 matrices, we have to divide the portion of the matrix into three parts.

1.) center

2.) corners

3.) rest

as we know the element present in the center, have to participate in four sums(two diagonal + one horizontal + one vertical) and there is only one number which satisfies this condition and it is 5. so 5 has its fixed position.

if we consider corners then every corner participate in three sums(one diagonal + one horizontal + one vertical) and from the range [1:9] only even numbers are able to do that work.

all the positions filled by odd numbers(except 5) because they are only who can participate in two sums(one horizontal + one vertical).

for some more inspection, we know that 1 and 9, 3 and 7 are opposite to each other and from the same way 2 and 8 and, 4 and 6 are opposite to each other.

by considering all these cases you can generate total 8 possible matrices.

transform the given matrix into any of them such that the cost is low.

method 2 :)

another way is that you can generate all matrixes and check if it is a magic square and how much cost you have to pay to reach up to this magic square from a given matrix. minimum from all the answers is your answer.

rishup132 last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.