(1)
Constructing Sudoku using backtracking
#include <iostream>#include <cstring>#include <ctime>#include <cstdio>#include <cstdlib>using namespace std;int sudu[9][9];void sudu_print(int sudu[][9]) { for(int i = 0; i < 9; ++i) { for(int j = 0; j < 9; ++j) { cout << " " << sudu[i][j]; } cout << endl; };}bool is_digital_sudu(int sudu[][9], int i, int j) { for(int k = 0; k < 9; ++k) { if(k == j) continue; if(sudu[i][k] == sudu[i][j]) return false; } for(int k = 0; k < 9; ++k) { if(k == i) continue; if(sudu[k][j] == sudu[i][j]) return false; } int p = i / 3; int q = j / 3; for(int m = 3 * p; m < 3 * p + 3; ++m) { for(int n = 3 * q; n < 3 * q + 3; ++n) if(m != i && n != j && sudu[m][n] == sudu[i][j]) return false; } return true;}int main() { srand(time(0)); memset(sudu, 0, sizeof(sudu)); for(int i = 0; i < 9; ++i) { int temp = rand() % 81; sudu[temp/9][temp%9] = i + 1; } int k = 0; while(1) { int x = k / 9; int y = k % 9; while(1) { sudu[x][y]++; if(sudu[x][y] == 10) { sudu[x][y] = 0; --k; break; }else if(is_digital_sudu(sudu, x, y)) { k++; break; } } if(81 == k) { sudu_print(sudu); return 0; } } return 0;}
In Linux, run the command: G ++ file name. cpp. If the program is not incorrect, a file:. Out is automatically generated under this directory. Therefore, execute the following command in this directory:
./A. Out
(2)
The replacement method in the book is simple ......
1.15 construction of sudoku