使用C++遍历所有九宫格横竖斜=15的数字组合

使用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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值