varchess;varstart;varend;//Create a chessboardfunctioncreatchess () {Chess=NewArray (); for(vari = 0; I < 9; i++) {Chess[i]=NewArray (); for(varj = 0; J < 9; J + +) {Chess[i][j]= 0; } }}//Print Boardfunctionprintchess () {varSay = ""; for(vari = 0; I < 9; i++) { for(varj = 0; J < 9; J + +) {say+=Chess[i][j]; } Say+ = ' \ n '; } console.log (say);}//detect cross-conflictfunctionCheckrow (r,c) { for(vari = 0; I < 9; i++) { if(i = =c) {Continue;//The same lattice jumps over } if(Chess[r][i] = =Chess[r][c]) { return false;//Conflict } } return true;//No conflict}//Detecting column ConflictsfunctionCheckcol (r,c) { for(vari = 0; I < 9; i++) { if(i = =r) {Continue;//The same lattice jumps over } if(Chess[i][c] = =Chess[r][c]) { return false;//Conflict } } return true;//No conflict}//detecting Small Block nine collisionsfunctionCheckarea (r,c) {varleft = Math.floor (R/3);vartop = Math.floor (C/3); for(vari = left; i < left+3; i++) { for(varj = Top; J < Top+3; J + +) { if(i = = r && J = =c) {Continue;//The same lattice jumps over } if(Chess[i][j] = =Chess[r][c]) { return false;//Conflict } } } return true;//No conflict}//get a random number of 1-9functionGetrandom () {returnMath.floor (Math.random () *9+1);}//Detection CorrectnessfunctionCheckok (r,c) {return(Checkrow (r,c) && checkcol (r,c) && Checkarea (r,c))?true:false;}//Initialize the boardfunctionChessinit () {Start=NewDate (). GetTime (); for(vari = 0; I < 9; i++) { varCount = 0; for(varj = 0; J < 9; J + +) {End=NewDate (). GetTime (); if(End-start > 500) {Console.log (' Ms Timeout!\n '); return; } if(count = = 0) Chess[i][j] = Getrandom ();//enter random numbers for the first time if(Count > 0) {Chess[i][j]++;//second entry to self-increment if(Chess[i][j] = = 10) {Chess[i][j]= 1;//return 1 } } if(count = = 9) chess[i][j] = 0;//1-9 are not available after authoring for 0 start backtracking if(Chess[i][j] = = 0) { if(J > 0) { //is not the first column to retrace the previous columnJ-= 2; Continue; } Else { //the first column goes backwards in the last rowi--; J= 8; Continue; } } //Check if it works if(Checkok (i, J)) {Count= 0;//Possible reset Counters } Else{Count++;//counter plus 1j--;//continue to } } }}//Initializefunctionchess () {creatchess ();//Create a chessboardChessinit ();//Initialize the boardPrintchess ();//Print Board}chess ();//sometimes the cycle of death is not resolved, so the execution time limit is added to prevent a dead loop.
Using JS traversal to generate Sudoku feasible data (bug version not optimized)