#include #include #include #include #include #include using namespace std; typedef vector< vector > grid; //there's only a handful of squares and they all are reflections or rotations of these ones: //4 9 2 //3 5 7 -> col 0 swap col 3, row 0 swap row 3 //8 1 6 // //6 7 2 //1 5 9 -> col 0 swap col 3, row 0 swap row 3 //8 3 4 // //4 3 8 //9 5 1 -> col 0 swap col 3, row 0 swap row 3 //2 7 6 grid A = { { 4, 9, 2}, { 3, 5, 7}, { 8, 1, 6}}; grid B = { { 6, 7, 2}, { 1, 5, 9}, { 8, 3, 4}}; grid C = { { 4, 3, 8}, { 9, 5, 1}, { 2, 7, 6}}; grid D = { {2, 9, 4}, {7, 5, 3}, {6, 1, 8}}; int operator-(const grid& lhs, const grid& rhs) { int total = 0; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) { if(lhs[i][j] != rhs[i][j]) { total+= abs(lhs[i][j] - rhs[i][j]); } } return total; } grid flipCols(const grid& other) { grid result = {{0,0,0}, {0,0,0}, {0,0,0}}; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(j == 0) result[i][2]=other[i][j]; else if(j == 2) result[i][0]=other[i][j]; else result[i][j]=other[i][j]; } } return result; } grid flipRows(const grid& other) { grid result = {{0,0,0}, {0,0,0}, {0,0,0}}; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(i == 0) result[2][j]=other[i][j]; else if(i == 2) result[0][j]=other[i][j]; else result[i][j]=other[i][j]; } } return result; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ //this actually causes a few duplicates, but it's not that many vector possibilities = {A, B, C, D}; for(int i = 0; i < 4; i++) { possibilities.emplace_back(flipCols(possibilities[i])); possibilities.emplace_back(flipRows(possibilities[i])); } grid input = {{0,0,0}, {0,0,0}, {0,0,0}}; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { cin >> input[i][j]; } } int min_cost = INT_MAX; for(const grid& g: possibilities) { int cost = g - input; if(cost < min_cost) min_cost = cost; } cout << min_cost << "\n"; return 0; }