#include #include #include #define SIZE 9 void generateMatrix(int matrix[SIZE][SIZE]); void printMatrix(int matrix[SIZE][SIZE]); int main() { int matrix[SIZE][SIZE] = {0}; srand(time(NULL)); generateMatrix(matrix); printMatrix(matrix); return 0; } void generateMatrix(int matrix[SIZE][SIZE]) { int row, col, num, count; int used[SIZE + 1]; // 标记每行是否已使用特定数字 for (row = 0; row < SIZE; row++) { for (int i = 1; i <= SIZE; i++) used[i] = 0; count = 0; while (count < 3) { num = rand() % SIZE + 1; col = rand() % SIZE; if (matrix[row][col] == 0 && used[num] == 0) { // 检查该数字和位置是否已使用 matrix[row][col] = num; used[num] = 1; count++; } } } // 确保每个3行的区块都包含1-9 for (int block = 0; block < SIZE; block += 3) { int numbers[SIZE + 1] = {0}; for (int r = block; r < block + 3; r++) { for (int c = 0; c < SIZE; c++) { int val = matrix[r][c]; if (val != 0) { numbers[val] = 1; } } } for (num = 1; num <= SIZE; num++) { if (numbers[num] == 0) { do { row = block + rand() % 3; col = rand() % SIZE; } while (matrix[row][col] != 0); matrix[row][col] = num; } } } } void printMatrix(int matrix[SIZE][SIZE]) { printf("|-------|-------|-------|\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (j % 3 == 0) printf("| "); if (matrix[i][j] == 0) { printf(". "); } else { printf("%d ", matrix[i][j]); } } printf("|\n"); if (i % 3 == 2) { printf("|-------|-------|-------|\n"); } } }