The basic framework of the <p> backtracking algorithm is </p><p> function name (int cnt) { </p><p> for () </p><p> {</p><p> assignment; </p><p>&nbs P if (= =) {</p><p> }ELSE{</P><P > function name (cnt+1);</p><p> &nbs P }</p><p> erase; </p><p> }& lt;/p><p>}</p>/* theme: Solving sudoku backtracking algorithm coder: Guepeng Zhi time:2015.1.11 * * #include <iostream>using NAMESP Ace std; #define N 9#include <math.h>class suduk{private:int sudu[n][n];p ublic:suduk (); void Setsudk ();//Input Sudoku Matrix BOOL Isvaild (int i,int j); void answer (int cnt); void Cout ();}; int main (void) {Suduk qus1;qus1. SETSUDK (); Qus1. Cout (); Qus1.answer (0); return 0;} void Suduk::couT () {for (int prin=0;prin<n*n;prin++) {if (prin%n = = 0) {Cout<<endl;} cout<<sudu[prin/n][prin%n]<< " ";} Cout<<endl;} Suduk::suduk () {for (int i=0;i<n*n;i++) {sudu[i/n][i%n]=0;}} void Suduk::setsudk () {int sudo[n][n]={{8,0,0,1,3,7,0,0,0},{6,0,0,9,0,0,0,1,0},{5,0,0,0,0,0,0,3,0},{ 0,0,0,3,8,0,0,0,9},{0,5,0,0,0,0,0,0,0},{9,0,0,0,0,0,8,7,0},{0,2,0,0,0,0,0,0,0},{0,0,0,0,0,6,2,4,3},{ 1,0,0,0,5,0,9,0,0}}; for (int. i=0;i<n;i++) {for (int j=0;j<n;j++) {sudu[i][j]=sudo[i][j]; CIN>>SUDU[I][J];} }}bool suduk::isvaild (int i,int j) {int run; for (run=0;run<n;run++) {if ((run!=j) &&sudu[i][run]==sudu[i][j]) {return false; } if ((Run!=i) &&sudu[run][j]==sudu[i][j]) {return false; }} int jie= (int) Pow ((double) n,1.0/2.0); int Row=i/jie*jie,col=j/jie*jie; for (run=0;run<n;run++) {if (Row+run/jie!=i | | Col+run%jie! = j) {if (Sudu[row+run/jie][col+run%jie]==sudu[i][j]) { return false; }}}retuRN true;} void Suduk::answer (int cnt) {int i=cnt/n;int j=cnt%n;if (sudu[i][j]==0) {for (int num=1;num<=n;num++) {Sudu[i][j]=num if (Isvaild (i,j)) {if (cnt!=n*n-1) {answer (cnt+1);} Else{cout ();}} sudu[i][j]=0;}} Else{answer (cnt+1);}}
The basic framework of backtracking algorithm is
function name (int cnt) {
for ()
{
if () {
}else{
Function name (cnt+1);
}
}
}
Backtracking algorithm (solving arbitrary order Sudoku)