想看个模板,大体的思路构建以及知识点的运用,如果可以的私,有偿的
模板是吗
#include <iostream>
#include <cstring>
using namespace std;
const int N = 9; // 数独方格大小为9x9
int board[N][N]; // 数独方格
bool row[N][N], col[N][N], box[N][N]; // 标记每行、每列和每个3x3小方格内已经出现的数字
// 判断当前位置是否可以填入数字num
bool isValid(int x, int y, int num) {
int box_x = x / 3, box_y = y / 3; // 计算当前位置所在的3x3小方格编号
return !row[x][num-1] && !col[y][num-1] && !box[box_x*3+box_y][num-1];
}
// 在当前位置填入数字num
void fill(int x, int y, int num) {
board[x][y] = num;
row[x][num-1] = true;
col[y][num-1] = true;
int box_x = x / 3, box_y = y / 3;
box[box_x*3+box_y][num-1] = true;
}
// 回溯搜索解法
bool dfs(int x, int y) {
if (x == N) return true; // 找到解
if (y == N) return dfs(x+1, 0); // 换行
if (board[x][y] != 0) return dfs(x, y+1); // 当前位置已经填入数字,跳过
for (int num = 1; num <= 9; num++) {
if (isValid(x, y, num)) {
fill(x, y, num); // 填入数字num
if (dfs(x, y+1)) return true; // 继续搜索
board[x][y] = 0;
row[x][num-1] = false;
col[y][num-1] = false;
int box_x = x / 3, box_y = y / 3;
box[box_x*3+box_y][num-1] = false; // 回溯
}
}
return false; // 无解
}
// 输出数独方格
void printBoard() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
int main() {
memset(row, false, sizeof(row));
memset(col, false, sizeof(col));
memset(box, false, sizeof(box));
// 输入数独方格,0表示空格
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> board[i][j];
if (board[i][j] != 0) {
row[i][board[i][j]-1] = true;
col[j][board[i][j]-1] = true;
int box_x = i / 3, box_y = j / 3;
box[box_x*3+box_y][board[i][j]-1] = true;
}
}
}
if (dfs(0, 0)) {
cout << "Solution:" << endl;
printBoard();
} else {
cout << "No solution." << endl;
}
return 0;
}
保证你们一篇看懂,不懂得可以留言!!!一定给你们讲明白!
include <iostream>
using namespace std;
class Base{
public:
Base(int d) : x(d){
cout << "create Base" << endl;
}
~Base(){
cout << "free Base" << endl;
}
private:
int x;
};
class Base1{
public:
Base1(int d) : y(d){
cout << "create Base1" << endl;
}
~Base1(){
cout << "free Base1" << endl;
}
private:
int y;
};
class Base2{
public:
Base2(int d) : z(d){
cout << "create Base2" << endl;
}
~Base2(){
cout << "free Base2" << endl;
}
private:
int z;
};
class D: **public** Base2, **public** Base1, **public** Base{
public:
D(int d):Base1(d), Base(d), Base2(d), b(d), b1(d), b2(d){
//编译不过
//Base1(d); //父类的构造函数必须是参数列表形式的
cout << "create D" << endl;
}
~D(){
cout << "free D" << endl;
}
private:
Base2 b;
Base1 b1;
Base b2;
};
int main(){
D d(10);
}
执行结果:
create Base2
create Base1
create Base
create Base2
create Base1
create Base
create D
free D
free Base
free Base1
free Base2
free Base
free Base1
free Base2
更多C++相关知识体系,请移步C++知识目录。