#include #include #include using namespace std; bool debug = false; int matrix_dist_3(int a[3][3], int b[3][3]){ int sum = 0; for (int i = 0; i < 3; ++i){ for (int j = 0; j < 3; ++j){ if(debug) cout << "i=" << i << ", j=" << j << ", a[i][j]=" << a[i][j] << ", b[i][j]=" << b[i][j] <<", dist=" << abs(a[i][j] - b[i][j]); sum += abs(a[i][j] - b[i][j]); if (debug) cout << ", running sum=" << sum << endl; } } return sum; } int min_dist_to_3_magic_square(int a[3][3]){ /* Find the minimum distance between the given matrix and a 3x3 magic square. There are only 8 magic squares for n=3, so just compare to each one. */ int min_dist = INT_MAX; int dist; int test[3][3]; string solutions[8]; solutions[0] = "618753294"; solutions[1] = "816357492"; solutions[2] = "276951438"; solutions[3] = "672159834"; solutions[4] = "492357816"; solutions[5] = "294753618"; solutions[6] = "834159672"; solutions[7] = "438951276"; for(int s = 0; s < 8; ++s){ //Build the test array from the solution string for(int i = 0; i < 3; ++i){ for(int j = 0; j < 3; ++j){ test[i][j] = solutions[s][3*i+j] - '0'; //convert char to it's int value } } dist = matrix_dist_3(a, test); if (debug) cout << dist << endl; if (dist < min_dist) min_dist = dist; } return min_dist; } int main(){ int input [3][3]; for(int i = 0; i < 3; ++i){ for(int j = 0; j < 3; ++j){ cin >> input[i][j]; } } cout << min_dist_to_3_magic_square(input); return 0; }