def CreateMagicSquare():
# 3x3 magic square 모든 경우의 수 생성
num = set(range(1, 10))
group = []
magic_square = []
for a in range(1, 10):
for b in range(1, 10):
for c in range(1, 10):
if (a + b + c == 15) & (a != b) & (a != c) & (b != c):
temp = [a, b, c]
group.append(temp)
for i in range(len(group)):
for j in range(len(group)):
for k in range(len(group)):
if set(group[i] + group[j] + group[k]) == num:
temp_a = group[i][0] + group[j][0] + group[k][0]
temp_b = group[i][1] + group[j][1] + group[k][1]
temp_c = group[i][2] + group[j][2] + group[k][2]
temp_d = group[i][0] + group[j][1] + group[k][2]
temp_e = group[i][2] + group[j][1] + group[k][0]
if temp_a == 15 & temp_b == 15 & temp_c == 15 & temp_d == 15 & temp_e == 15:
temp = []
temp.append(group[i])
temp.append(group[j])
temp.append(group[k])
magic_square.append(temp)
return magic_square
def formingMagicSquare(s):
magic_square = CreateMagicSquare()
cost_list = []
cost = 0
for n in range(len(magic_square)):
for i in range(3):
for j in range(3):
cost += abs(magic_square[n][i][j] - s[i][j])
cost_list.append(cost)
cost = 0
return min(cost_list)
if __name__ == '__main__':
s = []
for _ in range(3):
s.append(list(map(int, input().rstrip().split())))
result = formingMagicSquare(s)
print(result)
댓글