• + 1 comment

    The Fastest, concise, and most straight-forwarded Solution You will ever find across all discussion:

    include

    using namespace std;

    int main(){ int magic_sqr[8][9] = { {8,1,6,3,5,7,4,9,2}, {6,1,8,7,5,3,2,9,4}, {4,3,8,9,5,1,2,7,6}, {8,3,4,1,5,9,6,7,2}, {2,9,4,7,5,3,6,1,8}, {4,9,2,3,5,7,8,1,6}, {6,7,2,1,5,9,8,3,4}, {2,7,6,9,5,1,4,3,8} };

    int sqr[9];
    
    for(int i = 0; i < 9; i++){
        cin >> sqr[i];
    }
    
    int min_cost = 36; //'9 9 9 9 9 9 9 9 9' is converted to magic_sqr and it costs exactly 36 (absolute difference)
    
    for(int i = 0; i < 8; i++){
        int cost = 0;
        for(int j = 0; j < 9; j++){
            cost += abs(magic_sqr[i][j] - sqr[j]);
        }
        min_cost = min(cost, min_cost);
    }
    
    cout << min_cost << '\n';
    return 0;
    

    }