求解数独(回溯法)

//数独大概长这样
规则就是在空格中填写1~9的数字,每一行,每一列,还有每个区域(如上不同颜色的3*3区域)都只能由1~9的一组数字组成
也就是说同行,同类,同区域不能有相同的数字


input:
5 * * * * 7 * * 6
* 6 * * * * 5 * 4
* 8 3 4 * * * * *
* * * 1 8 2 * 4 *
* * 1 * * * 9 * *
* 7 * 3 6 9 * * *
* * * * * 5 4 3 *
1 * 5 * * * * 9 *
7 * * 2 * * * * 1

output:
5 1 4 9 2 7 3 8 6
9 6 7 8 3 1 5 2 4
2 8 3 4 5 6 1 7 9
6 5 9 1 8 2 7 4 3
3 2 1 5 7 4 9 6 8
4 7 8 3 6 9 2 1 5
8 9 2 6 1 5 4 3 7
1 3 5 7 4 8 6 9 2
7 4 6 2 9 3 8 5 1
//此为唯一解

不同的数独解不一定唯一,也不一定有解

#include<iostream>
#include<stdio.h>
#include<string>
#include<sstream>
#include<fstream>
#include<vector> 
#include<iomanip> 
#include<stack> 
#include<list>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
int num=0;
class point{
	public:
	int x;
	int y;
	point(int a,int b){
		x=a;
		y=b;
	}
};
//检查同行,同列,同区域内是否含有此数 
bool check(int a[9][9],int i,int j,int k){
		for(int x = 0;x<=8;x++){
		 	if(a[x][j]==k){
		 	return false;
			}
		}
		for(int x = 0;x<=8;x++){
		 	if(a[i][x]==k){
		 		return false;
			}
		}
		for(int p=(i/3)*3;p<(i/3)*3+3;p++){
			for(int q=(j/3)*3;q<(j/3)*3+3;q++){
				if(a[p][q]==k){
					return false;
				}	
			}
		}
		 return true;
} 

void out(int a[9][9]){
	for(int i=0;i<9;i++){
		for(int j=0;j<9;j++){
			cout<<a[i][j]<<" ";
		}cout<<endl;
	}
}


void solve(int a[9][9],vector<point>&v,int cur){
	if(cur==v.size()){
		out(a);
		cout<<endl;
		return;
	}
		for(int k=1;k<=9;k++){
			if(check(a,v[cur].x,v[cur].y,k)){
				a[v[cur].x][v[cur].y]=k;
				solve(a,v,cur+1);
				a[v[cur].x][v[cur].y]=0;
			}
		}
		return;
}
int main(){
	int a[9][9];
	vector<point>v;//记录要填空的坐标 
	
	for(int i=0;i<9;i++){
		for(int j =0;j<9;j++){
			cin>>a[i][j];
			if(a[i][j]==0){
				point p = point(i,j);
				v.push_back(p);
			}
		}
	} 
	solve(a,v,0);
	return 0;
} 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值