以下是一个生成数独的程序,利用深度优先遍历的方式。当生成9x9的的数独时,我的个人电脑需要花费的时间太长,而3x3和6x6的可以正确生成。
//mySIZE是数独棋盘的边长,棋盘是mySIZE*mySIZE的大小 int mySIZE = 9; void print(const vector<vector<int>> &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<vector<int>> &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 (int 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<vector<int>> &num, int row, int col) { vector<int> 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<vector<int>> num(mySIZE, vector<int>(mySIZE, -1)); generate_core(num, 0, 0); print(num); }
原文地址:http://blog.csdn.net/bupt8846/article/details/43503447