#include #include #include #include void swap(int *x, int *y); int main(void) { int cost[8]; int square[3][3]; for( int i = 0; i < 3; i++ ) { for( int j = 0; j < 3; j++ ) { scanf("%i", &square[i][j]); } } int matrix[3][3]; matrix[0][0] = 8; matrix[0][1] = 1; matrix[0][2] = 6; matrix[1][0] = 3; matrix[1][1] = 5; matrix[1][2] = 7; matrix[2][0] = 4; matrix[2][1] = 9; matrix[2][2] = 2; for( int k = 0; k < 8; k++ ) { cost[k] = 0; if( k == 1 ) { for( int i = 0; i < 3; i++ ) { swap(&matrix[i][0], &matrix[i][2]); } }else if( k == 2) { for( int i = 0; i < 3; i++ ) { swap( &matrix[0][i], &matrix[2][i] ); } }else if( k == 3) { for( int i = 0; i < 3; i++ ) { swap(&matrix[i][0], &matrix[i][2]); } }else if( k == 4 ) { matrix[0][0] = 8; matrix[0][1] = 3; matrix[0][2] = 4; matrix[1][0] = 1; matrix[1][1] = 5; matrix[1][2] = 9; matrix[2][0] = 6; matrix[2][1] = 7; matrix[2][2] = 2; }else if( k == 5 ) { for( int i = 0; i < 3; i++ ) { swap(&matrix[i][0], &matrix[i][2]); } }else if( k == 6 ) { for( int i = 0; i < 3; i++ ) { swap( &matrix[0][i], &matrix[2][i] ); } }else if( k == 7 ) { for( int i = 0; i < 3; i++ ) { swap(&matrix[i][0], &matrix[i][2]); } } for( int i = 0; i < 3; i++ ) { for( int j = 0; j < 3; j++ ) { if( square[i][j] != matrix[i][j] ) cost[k]+= abs(square[i][j] - matrix[i][j] ); } } } int min = cost[0]; for( int i = 1; i < 8; i++ ) { if( cost[i] < min ) min = cost[i]; } printf("%i\n", min); return 0; } void swap(int *x, int *y) { int a = *x; *x = *y; *y = a; }