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.

72 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 9
#define FILLED_NUMS 3
void initializeBoard(int board[SIZE][SIZE]) {
// 填充前3行包含1-9所有数字
int used[SIZE] = { 0 }; // 记录已使用的数字
for (int i = 0; i < 3; i++) {
// 清空used数组
for (int j = 0; j < SIZE; j++) {
used[j] = 0;
}
int count = 0;
while (count < FILLED_NUMS) {
int num = rand() % SIZE + 1; // 生成1到9之间的随机数
if (!used[num - 1]) { // 如果该数字未使用
board[i][rand() % SIZE] = num; // 在随机位置填入数字
used[num - 1] = 1; // 标记该数字为已使用
count++;
}
}
}
// 填充第4-6行与第7-9行
for (int i = 3; i < SIZE; i++) {
// 每行填充三个随机数,确保每行的数字互不相同
for (int j = 0; j < SIZE; j++) {
board[i][j] = 0; // 初始化为0
}
int used[SIZE] = { 0 }; // 记录这一行已使用的数字
int count = 0;
while (count < FILLED_NUMS) {
int num = rand() % SIZE + 1; // 生成1到9之间的随机数
if (!used[num - 1]) { // 如果该数字未使用
board[i][rand() % SIZE] = num; // 在随机位置填入数字
used[num - 1] = 1; // 标记该数字为已使用
count++;
}
}
}
}
void printSudoku(int board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (j % 3 == 0 && j != 0) {
printf("| ");
}
if (board[i][j] == 0) {
printf(". "); // 用'.'表示空白
}
else {
printf("%d ", board[i][j]);
}
}
printf("\n");
if ((i + 1) % 3 == 0 && i != 8) {
printf("---------------------\n");
}
}
}
int main() {
srand(time(NULL)); // 重置随机数种子
int board[SIZE][SIZE] = { 0 }; // 初始化9×9数组
initializeBoard(board); // 随机生成不完整数独矩阵
printSudoku(board); // 格式化输出
return 0;
}