diff --git a/second.c b/second.c new file mode 100644 index 0000000..8a13b93 --- /dev/null +++ b/second.c @@ -0,0 +1,72 @@ +#include +#include +#include + +#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; +} \ No newline at end of file