#include #include #include #include #include using namespace std; int n = 3; int ans = 9999; int a[4][4], p[10]; inline bool check () { bool res = 1; res &= (p[1] + p[2] + p[3] == 15); res &= (p[4] + p[5] + p[6] == 15); res &= (p[7] + p[8] + p[9] == 15); res &= (p[1] + p[5] + p[9] == 15); res &= (p[3] + p[6] + p[9] == 15); res &= (p[2] + p[5] + p[8] == 15); res &= (p[1] + p[4] + p[7] == 15); res &= (p[3] + p[5] + p[7] == 15); return res; } inline int cost () { int res = 0; for (int i = 1;i <= n;i ++) { for (int j = 1;j <= n;j ++) { res += abs(p[(i-1) * n + j] - a[i][j]); } } return res; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ for (int i = 1;i <= n;i ++) for (int j = 1;j <= n;j ++) cin >> a[i][j]; for (int i = 1;i <= n*n;i ++) p[i] = i; do { if (check ()) ans = min (ans, cost ()); } while (next_permutation (p + 1,p + 10)); cout << ans; return 0; }