Topic description
Two solutions are provided below, both of which are essentially all permutations of enumeration
Solution one
#include <iostream>
#include <algorithm>
using namespace std;
int ans;
bool st[10];
int p[10];
void dfs(int u) {
if (u > 8) {
int x = p[0] + p[1] + p[2] + p[3];
int y = p[3] + p[4] + p[5] + p[6];
int z = p[6] + p[7] + p[8] + p[0];
if (x == y && y == z ) ans ++;
return;
}
for (int i = 1; i <= 9; i++) {
if (!st[i]) {
st[i] = true;
p[u] = i;
dfs(u+1);
st[i] = false;
}
}
}
int main() {
dfs(0);
cout << ans / 6; // 144
return 0;
}
Solution two
#include <iostream>
#include <algorithm>
using namespace std;
int ans;
int main() {
int a[9] = {
1, 2, 3, 4, 5, 6, 7, 8, 9};
int x = a[0] + a[1] + a[2] + a[3];
int y = a[3] + a[4] + a[5] + a[6];
int z = a[6] + a[7] + a[8] + a[0];
if (x == y && y == z ) ans ++;
while (next_permutation(a, a+9)) {
int x = a[0] + a[1] + a[2] + a[3];
int y = a[3] + a[4] + a[5] + a[6];
int z = a[6] + a[7] + a[8] + a[0];
if (x == y && y == z ) ans ++;
}
cout << ans / 6;
return 0;
}