diff --git a/sudoku3.c b/sudoku3.c new file mode 100644 index 0000000..9404927 --- /dev/null +++ b/sudoku3.c @@ -0,0 +1,121 @@ +/*-------------------*/ +/*实验:数独矩阵------*/ +/*3. 判断一个不完整的矩阵是否满足“数独矩阵”的定义:*/ +/*-------------------*/ +#include +#include +#include +void randseedInit(){ + srand(time(NULL)); +} +void makeNSeq(int _seq[],int n){//产生1-n的不重复序列(传入一个数组名指针) + int ct[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; + int i; + for ( i = 0; i < n; i++) { + int t = rand() % n; + while(ct[t=rand() % n]); + ct[t]++; + _seq[i] = t+1; + } +} +void initBoard(int _board[9][9]){ + int i,j; + for ( i = 0; i < 9;i++) + for ( j = 0; j < 9;j++) + _board[i][j] = 0; +} +void makeRandomBoard(int _board[9][9]){ + initBoard(_board); + int i_1; + for (i_1 = 0; i_1 < 3;i_1++){ + int seq[9]; + makeNSeq(seq, 9); + int i; + for (i = 0; i < 3;i++){ + int where[9]; + makeNSeq(where, 9); + int idx; + for ( idx = 0; idx < 3;idx++){ + _board[i_1 * 3 + i][where[idx+i*3]-1] = seq[idx+i*3]; + } + } + } +} +void printWhyInvalid(int num,int is_col,int index,int *needprint){ + if(*needprint){ + printf("False:Invalid initial Sudoku matrix!\n The number %d in the %s %d has been used!\n", num, (is_col ? "col" : "block"), index); + *needprint = 0; + }; +} +int whoBeUsedInSeq(int seq[9]){ + int ct[10]={0,0,0,0,0,0,0,0,0,0}; + int i; + for ( i = 0; i < 9;i++){ + ct[seq[i]]++; + } + for (i = 1; i < 10;i++){ + if(ct[i]>1) + return i; + } + return 0; +} +void matrixT(int _board[9][9],int _output[9][9]){ + int i,j; + for ( i = 0; i < 9;i++) + for ( j = 0; j < 9;j++) + _output[j][i] = _board[i][j]; +} +void resortByBlock(int _board[9][9], int _output[9][9]) { + int i,j; + for ( i = 0; i < 9;i++){ + int p1x = i / 3; + int p1y = i % 3; + for ( j = 0; j < 9; j++){ + int p2x = j / 3; + int p2y = j % 3; + _output[i][j] = _board[p1x * 3 + p2x][p1y * 3 + p2y]; + } + } +} +int judgeValidInit(int _board[9][9]){ + int needprint = 1; + int boardT[9][9]; + int boardB[9][9]; + matrixT(_board, boardT); + resortByBlock(_board, boardB); + int i; + for ( i = 0; i < 9;i++){ + int who = whoBeUsedInSeq(boardT[i]); + if(who) + printWhyInvalid(who, 1, i+1, &needprint); + who = whoBeUsedInSeq(boardB[i]); + if(who) + printWhyInvalid(who, 0, i+1, &needprint); + } + return needprint; +} +void printBoad(int _board[9][9]){ + int i,j; + for ( i = 0; i < 9;i++){ + if(!(i%3))printf("|-----------------------|\n"); + for ( j = 0; j < 9;j++){ + if(!(j%3)) + printf("| "); + if(_board[i][j]==0) + printf(". "); + else + printf("%d ", _board[i][j]); + } + printf("|\n"); + } + printf("|-----------------------|\n"); +} +int main(){ + randseedInit(); + int board[9][9]; + makeRandomBoard(board); + printf("The original Sudoku matrix:\n"); + printBoad(board); + if(judgeValidInit(board))printf("True:Valid initial Sudoku matrix!\n"); + +}