加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

一个随机生成数独的C++程序

发布时间:2020-12-16 07:47:49 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 //mySIZE是数独棋盘的边长,棋盘是mySIZE*mySIZE的大小int mySIZE = 9;void print(const vectorvectorint num){for (int i = 0; i mySIZE; i++){for (

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

//mySIZE是数独棋盘的边长,棋盘是mySIZE*mySIZE的大小
int mySIZE = 9;

void print(const vector<vector<int>> &num)
{
	for (int i = 0; i < mySIZE; i++)
	{
		for (int j = 0; j < mySIZE; j++)
		{
			cout << num[i][j] << " ";
		}
		cout << endl;
	}
}

bool IsRightPlace(vector<vector<int>> &num,int row,int col)
{
	int n = num[row][col];
	//注意i < row
	for (int i = 0; i < row; i++)
	{
		if (num[i][col] == n)
			return false;
	}
	//注意i < col
	for (int i = 0; i < col; i++)
	{
		if (num[row][i] == n)
			return false;
	}
	int row_start = row / 3;
	row_start *= 3;
	int row_end = row_start + 2;
	int col_start = col / 3;
	col_start *= 3;
	int col_end = col_start + 2;
	int i = row_start,j = col_start;
	//注意 k <= 8
	for (int k = 1; k <= 8; k++)
	{
		if (row != i || col != j)
		{
			if (num[i][j] == n)
				return false;
		}
		else
			break;
		if (j == col_end)
		{
			//注意j = col_start !不要搞错换行时列的起始点!
			j = col_start;
			i = i + 1;
		}
		else
		{
			j = j + 1;
		}
	}
	return true;
}

bool generate_core(vector<vector<int>> &num,int col)
{
	
	vector<int> number;
	for (int i = 1; i <= 9; i++)
		number.emplace_back(i);
	while (!number.empty())
	{
		int randindex = rand() % number.size();
		int randnum = number[randindex];
		number.erase(number.begin() + randindex);
		num[row][col] = randnum;
		if (IsRightPlace(num,row,col) == false)
			continue;
		if (row == mySIZE - 1 && col == mySIZE-1)
		{
			return true;
		}
		int nextrow,nextcol;
		if (col == mySIZE-1)
		{
			nextrow=row + 1;
			nextcol = 0;
		}
		else
		{
			nextrow = row;
			nextcol = col + 1;
		}
		bool next = generate_core(num,nextrow,nextcol);
		if (next)
			return true;
	}
	if (number.empty())
	{
		num[row][col] = -5;
		return false;
	}		
}

void generate()
{
	vector<vector<int>> num(mySIZE,vector<int>(mySIZE,-1));
	srand((unsigned)time(NULL));
	if( generate_core(num,0) )
		print(num);
}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读