#include #include #include #include #include using namespace std; int permu[11], mat[5][5], row[5], col[5], res = 100000000, tmp, ori[5][5]; int dia1, dia2; void setup() { int cnt = 0; tmp = 0, dia1 = 0, dia2 = 0; for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) mat[i][j] = permu[++cnt], tmp += abs(permu[cnt] - ori[i][j]); row[i] = col[i] = 0; } } /* 1 5 9 2 6 7 3 4 8 */ bool check() { for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) { row[i] += mat[i][j]; col[j] += mat[i][j]; if(i == j) dia1 += mat[i][j]; if(i == 3 - j + 1) dia2 += mat[i][j]; } } return row[1] == row[2] && row[1] == row[3] && row[1] == col[1] && col[1] == col[2] && col[2] == col[3] && col[3] == dia1 && dia1 == dia2; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ for(int i = 1; i <= 9; i++) permu[i] = i; for(int i = 1; i <= 3; i++) for(int j = 1; j <= 3; j++) cin >> ori[i][j]; do { setup(); if(check()) { res = min(res, tmp); } } while(next_permutation(permu + 1, permu + 9 + 1)); cout << res; return 0; }