A
Constructing Sudoku with backtracking method
#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 &&A mp 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] = = Ten) {Sudu[x][y] = 0; --k; Break }else if (Is_digital_sudu (Sudu, x, y)) {k++; Break }} if (Bayi = = k) {sudu_print (Sudu); return 0; }} return 0;}
To run under Linux, run the command first: g++ file name. cpp then assume that the program has no errors. Then in this folder the following will voluntarily generate a file:. Out.
So this time continue to run under this folder:
./a.out
Two
The method of using the permutation on the book is simple.
。
。。
。
。
1.15 Construction Sudoku