传送门:牛客
题目描述:
玩家需要根据 9×9 盘面上的已知数字,推理出所有剩余位置的数字,并满足每一行、每一列、每一个粗线九宫格内的数字包含有 1-9 的数字,且不重复。
现在给你一个数独,请你解答出来。每个数独保证有且只有一个解。
输入:
5 3 0 0 7 0 0 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9
输出:
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
这道题的题面还是挺吸引人的,是一道解决数独的题目诶,以后碰到数独不就直接秒杀??
不过言归正传,这道题目经过分析一下之后会发现应该是一道搜索的题目(因为N才只有9,应该是不会超时的)
对于我们的搜索过程,我们直接从第一个位置开始搜,然后碰到有数字的地方就下一个,对于没有数字的地方我们直接枚举1~9
这9个数字,对于每一个数字我们直接枚举这一个数字所在的行,所在的列,所在的一个9*9
的范围即可.
下面是具体的代码部分:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string.h>
#include <stack>
#include <deque>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define root 1,n,1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
inline ll read() {
ll x=0,w=1;char ch=getchar();
for(;ch>'9'||ch<'0';ch=getchar()) if(ch=='-') w=-1;
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x*w;
}
#define maxn 1000000
#define ll_maxn 0x3f3f3f3f3f3f3f3f
const double eps=1e-8;
int mp[100][100];
int check(int i,int j,int k) {
for(int y=1;y<=9;y++) {
if(mp[i][y]==k) return false;
}
for(int x=1;x<=9;x++) {
if(mp[x][j]==k) return false;
}
int ii=(i-1)/3+1,jj=(j-1)/3+1;
for(int x=(ii-1)*3+1;x<=(ii-1)*3+3;x++) {
for(int y=(jj-1)*3+1;y<=(jj-1)*3+3;y++) {
if(mp[x][y]==k) return false;
}
}
return true;
}
void dfs(int n) {
if(n==82) {
for(int i=1;i<=9;i++) {
for(int j=1;j<=9;j++) {
printf("%d ",mp[i][j]);
}
printf("\n");
}
return ;
}
int i=(n-1)/9+1,j=(n-1)%9+1;
if(mp[i][j]!=0) dfs(n+1);
else {//注意这个else,我之前没加然后一直过不去
for(int k=1;k<=9;k++) {
if(check(i,j,k)) {
mp[i][j]=k;
dfs(n+1);
mp[i][j]=0;//此处是需要回溯的,不然会影响下一次的判断
}
}
}
return ;
}
int main() {
for(int i=1;i<=9;i++) {
for(int j=1;j<=9;j++) {
mp[i][j]=read();
}
}
dfs(1);
return 0;
}