728x90
반응형
1. Problem
2. Feedback
- 3*3의 마방진은 답이 정해져있다.
- 정해진 답 속에서 입력받은 square 를 하나씩 비교해서 cost 를 계산한다. 제일 낮은 값이 정답이다.
3. Source
public class FormingAMagicSquare
{
private static int answer[][] =
{
{2,9,4,7,5,3,6,1,8},
{4,3,8,9,5,1,2,7,6},
{4,9,2,3,5,7,8,1,6},
{8,3,4,1,5,9,6,7,2},
{8,1,6,3,5,7,4,9,2},
{2,7,6,9,5,1,4,3,8},
{6,1,8,7,5,3,2,9,4},
{6,7,2,1,5,9,8,3,4},
};
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int square[][] = new int[3][3];
for (int i = 0 ; i < 3 ; i++)
{
for (int j = 0 ; j < 3 ; j++)
{
square[i][j] = in.nextInt();
}
}
int result = solve(square);
System.out.println(result);
}
public static int solve(int square[][])
{
int cost[] = new int[8];
for (int i = 0 ; i < 8 ; i++)
{
cost[i] += Math.abs(answer[i][0] - square[0][0]) + Math.abs(answer[i][1] - square[0][1]) + Math.abs(answer[i][2] - square[0][2]);
cost[i] += Math.abs(answer[i][3] - square[1][0]) + Math.abs(answer[i][4] - square[1][1]) + Math.abs(answer[i][5] - square[1][2]);
cost[i] += Math.abs(answer[i][6] - square[2][0]) + Math.abs(answer[i][7] - square[2][1]) + Math.abs(answer[i][8] - square[2][2]);
}
Arrays.sort(cost);
return cost[0];
}
public static void printSquare(int square[][])
{
for (int i = 0 ; i < 3 ; i++)
{
for (int j = 0 ; j < 3 ; j++)
{
System.out.print(square[i][j] + " ");
}
System.out.println();
}
}
}
'algorithm > hackerRank' 카테고리의 다른 글
[HackerRank] Sock Merchant (0) | 2018.10.11 |
---|---|
[HackerRank] Organizing Containers of Balls (0) | 2018.07.12 |
[HackkerRank] DP: Coin Change (0) | 2018.06.26 |
[HackkerRank] Recursion: Davis' Staircase (0) | 2018.06.26 |
[HackkerRank] Hash Tables: Ice Cream Parlor (0) | 2018.06.25 |
댓글