AcWing 3162. 九宫幻方
原题链接
简单
作者:
Nazarena
,
2021-01-22 23:27:08
,
所有人可见
,
阅读 529
C++ 代码
#include<bits/stdc++.h>
using namespace std;
int a[3][3];
int sum = 0;
void method1()
{
int t,res,x,y;
for(int i=0;i<3;i++)
{
t = 0;
res = 0;
for(int j=0;j<3;j++)
{
if(a[i][j] != 0)
{
t++;
res += a[i][j];
}
else
y = j;
}
if(t == 2)
{
a[i][y] = 15 - res;
sum ++;
}
}
}
void method2()
{
int t,res,x,y;
for(int i=0;i<3;i++)
{
t = 0;
res = 0;
for(int j=0;j<3;j++)
{
if(a[j][i] != 0)
{
t++;
res += a[j][i];
}
else
x = j;
}
if(t == 2)
{
a[x][i] = 15 - res;
sum ++;
}
}
}
void method()
{
a[1][1] = 5;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(a[i][j] != 0 && i != 1 && j != 1 && a[2-i][2-j] == 0)
{
a[2-i][2-j] = 10 - a[i][j];
sum ++;
}
}
while(1)
{
method1();
method2();
if(sum == 8)
break;
}
}
int main()
{
int i,j,flag = 0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cin >> a[i][j];
if(a[1][1] != 0)
sum -= 1;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
if(a[i][j] != 0)
sum++;
if(sum == 4 && a[0][0] == 0 && a[0][2] == 0 && a[2][0] == 0 && a[2][2] == 0)
{
if(a[1][0] == 3 && a[0][1] == 9)
a[0][0] = 4;
else if(a[1][0] == 1 && a[0][1] == 3)
a[0][0] = 8;
else if(a[1][0] == 7 && a[0][1] == 1)
a[0][0] = 6;
else if(a[1][0] == 9 && a[0][1] == 7)
a[0][0] = 2;
else if(a[1][0] == 3 && a[0][1] == 9)
a[0][0] = 4;
else if(a[1][0] == 1 && a[0][1] == 7)
a[0][0] = 8;
else if(a[1][0] == 7 && a[0][1] == 9)
a[0][0] = 2;
else if(a[1][0] == 9 && a[0][1] == 3)
a[0][0] = 4;
sum++;
method();
}
else if(sum >= 3)
method();
else
{
if(a[0][0] != a[2][2])
flag ++;
if(a[0][1] != a[2][1])
flag ++;
if(a[0][2] != a[2][0])
flag ++;
if(a[1][0] != a[1][2])
flag ++;
if(flag == 2)
method();
else
{
cout << "Too Many";
return 0;
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}