A program that generates data independence
The following is a program to generate a Sudoku, which uses the depth-first Traversal method. When 9x9 is generated, it takes too long for my PC, while 3x3 and 6x6 can be generated correctly.
// MySIZE is the edges of the sudoku board, and the chessboard is the size of mySIZE * mySIZE int mySIZE = 9; void print (const vector
> & Num) {for (int I = 0; I <mySIZE; I ++) {for (int j = 0; j <mySIZE; j ++) {cout <num [I] [j] <"\ t" ;}cout <endl ;}} bool IsRightPlace (vector
> & Num, int row, int col) {int n = num [row] [col]; for (int I = 0; I <mySIZE; I ++) {if (I = row) continue; if (num [I] [col] = n) return false;} for (int I = 0; I <mySIZE; I ++) {if (I = col) continue; if (num [row] [I] = n) return false;} int row_start = row/3; row_start * = 3; int row_end = row_start + 2; int col_start = col/3; col_start * = 3; int col_end = col_start + 2; int I = row_start, j = col_start; for (I Nt k = 1; k <= 9; k ++) {if (row! = I | col! = J) {if (num [I] [j] = n) return false;} if (j = col_end) {j = 0; I = I + 1 ;} else {j = j + 1 ;}} return true;} bool generate_core (vector
> & Num, int row, int col) {vector
Number; for (int I = 1; I <= 9; I ++) number. emplace_back (I); while (! Number. empty () {int randindex = rand () % number. size (); int randnum = number [randindex]; number. erase (number. begin () + randindex); num [row] [col] = randnum; if (IsRightPlace (num, row, col) = false) continue; if (row = mySIZE-1 & col = mySIZE-1) {return true;} int nextrow, nextcol; if (col = mySIZE-1) {nextrow = row + 1; nextcol = 0;} else {nextrow = row; nextcol = col + 1;} bool next = generate_core (num, nextrow, nextcol); if (next) return true ;} if (number. empty () {num [row] [col] =-5; return false ;}} void generate () {vector
> Num (mySIZE, vector
(MySIZE,-1); generate_core (num, 0, 0); print (num );}