You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
117 lines
2.7 KiB
117 lines
2.7 KiB
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
// 函数用于生成数字1到9的随机排列
|
|
void shuffle(int arr[], int n) {
|
|
if (n > 1) {
|
|
int i;
|
|
for (i = 0; i < n - 1; i++) {
|
|
int j = i + rand() % (n - i);
|
|
int temp = arr[i];
|
|
arr[i] = arr[j];
|
|
arr[j] = temp;
|
|
}
|
|
}
|
|
}
|
|
//数独矩阵比较美观的输出
|
|
void printSudoku(int sudoku[9][9]) {
|
|
printf("+-------+-------+-------+\n");
|
|
for (int i = 0; i < 9; i++) {
|
|
if (i > 0 && i % 3 == 0) {
|
|
printf("+-------+-------+-------+\n");
|
|
}
|
|
for (int j = 0; j < 9; j++) {
|
|
if (j % 3 == 0) {
|
|
printf("| ");
|
|
}
|
|
printf("%d ", sudoku[i][j]); // 输出数组中的元素
|
|
}
|
|
printf("|\n");
|
|
}
|
|
printf("+-------+-------+-------+\n");
|
|
}
|
|
int main() {
|
|
// 初始化随机数生成器
|
|
srand(time(0));
|
|
|
|
int grid[9][9] = {0}; // 创建3x9的数组并初始化为0
|
|
|
|
int numbers[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // 创建包含数字1到9的数组
|
|
|
|
// 随机排列数组中的数字
|
|
shuffle(numbers, 9);
|
|
|
|
int row, col;
|
|
int numIndex = 0;
|
|
|
|
// 将打乱顺序的数字填充到数组中
|
|
for (row = 0; row < 3; row++)
|
|
{
|
|
int aa=0,bb=0,cc=0;
|
|
while(aa==bb||bb==cc||aa==cc)
|
|
{
|
|
aa=rand()%9;
|
|
bb= rand()%9;
|
|
cc=rand()%9;
|
|
}
|
|
grid[row][aa] = numbers[numIndex];
|
|
numIndex++;
|
|
grid[row][bb] = numbers[numIndex];
|
|
numIndex++;
|
|
grid[row][cc] = numbers[numIndex];
|
|
numIndex++;
|
|
}
|
|
// 随机排列数组中的数字
|
|
shuffle(numbers, 9);
|
|
|
|
numIndex = 0;
|
|
|
|
// 将打乱顺序的数字填充到数组中
|
|
for (row = 3; row < 6; row++)
|
|
{
|
|
int aa=0,bb=0,cc=0;
|
|
while(aa==bb||bb==cc||aa==cc)
|
|
{
|
|
aa=rand()%9;
|
|
bb= rand()%9;
|
|
cc=rand()%9;
|
|
}
|
|
grid[row][aa] = numbers[numIndex];
|
|
numIndex++;
|
|
grid[row][bb] = numbers[numIndex];
|
|
numIndex++;
|
|
grid[row][cc] = numbers[numIndex];
|
|
numIndex++;
|
|
}
|
|
// 随机排列数组中的数字
|
|
shuffle(numbers, 9);
|
|
|
|
|
|
numIndex = 0;
|
|
|
|
// 将打乱顺序的数字填充到数组中
|
|
for (row = 6; row < 9; row++)
|
|
{
|
|
int aa=0,bb=0,cc=0;
|
|
while(aa==bb||bb==cc||aa==cc)
|
|
{
|
|
aa=rand()%9;
|
|
bb= rand()%9;
|
|
cc=rand()%9;
|
|
}
|
|
grid[row][aa] = numbers[numIndex];
|
|
numIndex++;
|
|
grid[row][bb] = numbers[numIndex];
|
|
numIndex++;
|
|
grid[row][cc] = numbers[numIndex];
|
|
numIndex++;
|
|
}
|
|
// 打印数组
|
|
printSudoku(grid);
|
|
|
|
return 0;
|
|
}
|
|
|
|
|