-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMagicSquare.java
68 lines (51 loc) · 1.91 KB
/
MagicSquare.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
static int formingMagicSquare(int[][] s) {
//O(1) Time and Space with precomputed values
int[][][] magix = {
{{8, 1, 6}, {3, 5, 7}, {4, 9, 2}},
{{6, 1, 8}, {7, 5, 3}, {2, 9, 4}},
{{4, 9, 2}, {3, 5, 7}, {8, 1, 6}},
{{2, 9, 4}, {7, 5, 3}, {6, 1, 8}},
{{8, 3, 4}, {1, 5, 9}, {6, 7, 2}},
{{4, 3, 8}, {9, 5, 1}, {2, 7, 6}},
{{6, 7, 2}, {1, 5, 9}, {8, 3, 4}},
{{2, 7, 6}, {9, 5, 1}, {4, 3, 8}},
};
int minCost = Integer.MAX_VALUE;
for(int matr = 0; matr < magix.length; matr++){
int cost = 0;
for(int row = 0; row < s.length; row++) {
for(int col = 0; col < s[row].length; col++) {
cost += Math.abs(s[row][col] - magix[matr][row][col]);
}
}
minCost = Math.min(cost, minCost);
}
return minCost;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int[][] s = new int[3][3];
for (int i = 0; i < 3; i++) {
String[] sRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 3; j++) {
int sItem = Integer.parseInt(sRowItems[j]);
s[i][j] = sItem;
}
}
int result = formingMagicSquare(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}