根据题目要求,由于我第二次作业写得代码没有类,不好调用函数,所以 基于第二次写数独的思想代码进行了重写改动。
Su1.cpp代码(数独代码)
#include "stdafx.h" #include "Su.h" #include "Su1.h" #include <iostream> #include <ctime> #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif CSu::CSu() { int i,j; for(i=1;i<10;i++) for(j=1;j<10;j++) map[i][j] = 0; } CSu::CSu(int n) //随机生成n个数字 { int i,j; for(i=1;i<10;i++) for(j=1;j<10;j++) map[i][j] = 0; srand((unsigned)time(0)); //每行初始一个 do { for(i=1;i<10;i++) { j = rand()%10; map[i][j] = i; } }while (!Check()); Solve();//填好 //挖空 int k = 0; while(1) { i=rand()%81; j=i%9; i=i/9; int x = map[i+1][j+1]; if(x>0) { map[i+1][j+1] = 0; k++; } if(k == 81-n) break; } } CSu::CSu(int data[9][9]) { int i,j; for(i=1;i<10;i++) for(j=1;j<10;j++) map[i][j] = data[i-1][j-1]; } CSu::~CSu() { return; } bool CSu::Check() { memset(sqr,false,sizeof(sqr)); memset(row,false,sizeof(sqr)); memset(col,false,sizeof(sqr)); int i,j; for(i=1;i<10;i++) for(j=1;j<10;j++) { int temp = map[i][j]; if( temp != 0) { if( !row[i][temp] ) row[i][temp] = true; else return false; if( !col[j][temp]) col[j][temp] = true; else return false; if( !sqr[(i-1)/3*3+(j-1)/3+1][temp] ) sqr[(i-1)/3*3+(j-1)/3+1][temp] = true; else return false; } } return true; } bool CSu::Solve() { int i,j; memset(sqr,false,sizeof(sqr)); memset(row,false,sizeof(sqr)); memset(col,false,sizeof(sqr)); for(i=1;i<=9;i++) for(j=1;j<=9;j++) { if(map[i][j]!=0) { row[i][map[i][j]]=true; col[j][map[i][j]]=true; //小正方形被标志为1--9; sqr[(i-1)/3*3+(j-1)/3+1][map[i][j]]=true; } } bool ans = DFS(); return ans; } bool CSu::DFS() { int i,j,k; for(i=1;i<10;i++) for(j=1;j<10;j++) { if(map[i][j]==0) { for(k=1;k<=9;k++) { if(!row[i][k]&&!col[j][k]&&!sqr[(i-1)/3*3+(j-1)/3+1][k]) { map[i][j]=k; row[i][k]=true; col[j][k]=true; sqr[(i-1)/3*3+(j-1)/3+1][k]=true; if(DFS()) return true; else { map[i][j]=0; row[i][k]=false; col[j][k]=false; sqr[(i-1)/3*3+(j-1)/3+1][k]=false; } } } if(k==10)return false; } } return true; }
Su1.h代码
#if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CSu { public: CSu(); CSu(int n); //随机生成数独,n个空格含有数字 CSu(int data[9][9]); virtual ~CSu(); bool Check(); bool Solve(); bool DFS(); int map[10][10]; private: bool row[10][10],col[10][10],sqr[10][10]; }; #endif
添加数独题目按钮代码
void CSuDlg::OnButton1() //数独题目按钮 { // TODO: Add your control notification handler code here int i,j; for(i=0;i<81;i++) { c[i].SetWindowText("0"); c[i].EnableWindow(1); } CSu s(40); char str[5]; int count = 0; for(i=1;i<=9;i++) for(j=1;j<=9;j++) { str[0]=s.map[i][j]+'0'; str[1]='