본문 바로가기

알고리즘/Hackerrank

[Hackerrank] Forming a Magic Square

We define a magic square to be an n x n matrix of distinct positive integers from 1 to n2 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 gicen a 3 x 3 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 |a-b|. Given s, convert it into a magic square at minimal cost. Print this cost on a new line.

 

Note : The resulting magic square must contain distinct integers in the inclusive range [1,9].

 

Example

 

$s = [[5,3,4], [1,5,8], [6,4,2]]

 

The matrix looks like this:

5 3 4
1 5 8
6 4 2

 

We can convert it to the following magic square:

 

8 3 4
1 5 9
6 7 2

 

This took three replacements at a cost of |5-8| + |8-9| + |4-7| = 7

 

Function Description

 

Complete the formingMagicSquare function in the editor below.

formingMagicSquare has the following parameter(s):

- int s[3][3]: a 3 x 3 array of integers

 

Returns

- int: the minimal total cost of converting the input square to a magic square

 

Input Format

Each of the 3 lines contains three space-separeted integers of row s[i].

 

Constraints

- s[i][j] [1,9]

 

Sample Input 0

4 9 2
3 5 7
8 1 5

 

Sample Output 0

1

 

Explanation 0

If we change the bottom rigth value, s[2][2], from 5 to 6 at a cost of |6-5| = 1, s becomes a magic sqyare at the minimum possible cost.

 

Sample Input 1

4 8 2
4 5 7
6 1 6

 

Sample Input 1

4

 

Explanation 1

Using 0-based indexing, if we make

- s[0][1]->0 at a cost of |9-8| = 1

- s[1][0]->3 at a cost of |3-4| = 1

- s[2][0]->8 at a cost of|8-6| = 2

then the total cost will be 1+1+2 = 4.

 

더보기

define : 정의하다

matrix : 행렬

positive : 양성

diagonal : 대각선

 

머리로해결할수없어서.. 그림을 그렸다..

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

class Result {

    /*
     * Complete the 'formingMagicSquare' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts 2D_INTEGER_ARRAY s as parameter.
     */

    public static int formingMagicSquare(List<List<Integer>> s) {
    // Write your code here
        int [] answer = new int[8];
        int [][] square1 = {{8,3,4},{1,5,9},{6,7,2}};
        int [][] square2 = {{8,1,6},{3,5,7},{4,9,2}};
        int [][] square3 = {{4,3,8},{9,5,1},{2,7,6}};
        int [][] square4 = {{6,1,8},{7,5,3},{2,9,4}};
        int [][] square5 = {{2,7,6},{9,5,1},{4,3,8}};
        int [][] square6 = {{2,9,4},{7,5,3},{6,1,8}};
        int [][] square7 = {{6,7,2},{1,5,9},{8,3,4}};
        int [][] square8 = {{4,9,2},{3,5,7},{8,1,6}};
        
        for(int i=0; i<3; i++) {
            for(int j=0; j<3; j++) {
                answer[0] += Math.abs(s.get(i).get(j) - square1[i][j]);
                answer[1] += Math.abs(s.get(i).get(j) - square2[i][j]);
                answer[2] += Math.abs(s.get(i).get(j) - square3[i][j]);
                answer[3] += Math.abs(s.get(i).get(j) - square4[i][j]);
                answer[4] += Math.abs(s.get(i).get(j) - square5[i][j]);
                answer[5] += Math.abs(s.get(i).get(j) - square6[i][j]);
                answer[6] += Math.abs(s.get(i).get(j) - square7[i][j]);
                answer[7] += Math.abs(s.get(i).get(j) - square8[i][j]);
            }
        }
        Arrays.sort(answer);
        return answer[0];
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        List<List<Integer>> s = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            String[] sRowTempItems = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

            List<Integer> sRowItems = new ArrayList<>();

            for (int j = 0; j < 3; j++) {
                int sItem = Integer.parseInt(sRowTempItems[j]);
                sRowItems.add(sItem);
            }

            s.add(sRowItems);
        }

        int result = Result.formingMagicSquare(s);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

'알고리즘 > Hackerrank' 카테고리의 다른 글

[Hackerrank] Operators  (0) 2021.09.25
[Hackerrank] Data Types  (0) 2021.09.25
[Hackerrank] Picking Numbers  (0) 2021.09.25
[Hackerrank] Java Loops 1  (0) 2021.09.23
[Hackerrank] Java Output Formatting  (0) 2021.09.23