题目描述:
将1-9这九个数字排成三行三列,使其行列、对角线上三数之和均相同,试编程求所有的可能;
#include <iostream>
using namespace std;
int a[3][3], b[3][3];
int main()
{
int i, tx, ty;
int x = 0, y = 1;
a[0][1] = 1; //将1放在第0行第1列
for (i = 2; i <= 9; i++)
{
tx = (x + 2) % 3;
ty = (y + 1) % 3;
if (a[tx][ty] == 0) //如果斜上方未填数字
{
a[tx][ty] = i; //x为行,y为列
x = tx;
y = ty;
}
else //否则填数到下方
{
x = (x + 1) % 3;
a[x][y] = i;
}
}
for (i = 0; i <= 3; ++i)
{
cout << a[0][0] << a[0][1] << a[0][2] << endl;
cout << a[1][0] << a[1][1] << a[1][2] << endl;