使用C++遍历所有九宫格横竖斜=15的数字组合
共找到8组
2 7 6 | 2 9 4 | 4 3 8 | 4 9 2 | 6 1 8 | 6 7 2 | 8 1 6 | 8 3 4 |
9 5 1 | 7 5 3 | 9 5 1 | 3 5 7 | 7 5 3 | 1 5 9 | 3 5 7 | 1 5 9 |
4 3 8 | 6 1 8 | 2 7 6 | 8 1 6 | 2 9 4 | 8 3 4 | 4 9 2 | 6 7 2 |
代码如下:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
#define M 3
void printArray(int a[M][M])
{
//输出找到的组合
for (int i = 0; i<M; i++)
{
for(int j = 0; j<M; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
bool columnIsEquual(int a[M][M])
{
//判断横竖向是否符合规则
if (a[0][0]+a[1][0]+a[2][0] == 15 &&
a[0][1]+a[1][1]+a[2][1] == 15 &&
a[0][2]+a[1][2]+a[2][2] == 15 &&
a[0][0]+a[0][1]+a[0][2] == 15 &&
a[1][0]+a[1][1]+a[1][2] == 15 &&
a[2][0]+a[2][1]+a[2][2] == 15 )
{
return true;
}
else
return false;
}
bool slantIsEquual(int a[M][M])
{
//判断斜向是否符合规则
int slantSum1 = a[0][0]+a[1][1]+a[2][2];
int slantSum2 = a[0][2]+a[1][1]+a[2][0];
if(slantSum1 != 15|| slantSum2 != 15)
return false;
else
return true;
}
void test()
{
int a[M][M];
int ngFlag = 0;
char ch1[10];
int m = 1;
for (unsigned int n = 123456789;n < 987654322;n++)
{
ngFlag = 0;
//将数字转换为数组
sprintf(ch1,"%d",n);
for (int i = 0; i<8; i++)
{
for (int j = i+1; j<9; j++)
//判断是否有0或者是否有等的数据
if (ch1[i] == ch1[j] || ch1[i+1] == '0')
{
ngFlag = 1;
break;
}
if (ngFlag == 1)
break;
}
if (ngFlag != 1)
{
cout << ch1 << endl;
int num = 0;
for (int i = 0; i<3; i++)
{
for (int j = 0; j<3; j++)
{
a[i][j] = ch1[num++]-48;
}
}
if(columnIsEquual(a) && slantIsEquual(a) )
{
//每找到一个数暂停一次
printArray(a);
cout << "----------" << m++ << "------------" << endl;
system("pause");
}
}
}
}
int main()
{
test();
system("pause");
return 0;
}