链接:https://ac.nowcoder.com/acm/contest/625/E
来源:牛客网
题目描述
数独是一种填数字游戏,英文名叫 Sudoku,起源于瑞士,上世纪 70 年代由美国一家数学逻辑游戏杂志首先发表,名为 Number Place,后在日本流行,1984 年将 Sudoku 命名为数独,即 “独立的数字” 的缩写,意思是 “在每一格只有一个数字”。
2004 年,曾任中国香港高等法院法官的高乐德 (Wayne Gould) 把这款游戏带到英国,成为英国流行的数学智力拼图游戏。
玩家需要根据
9×9 盘面上的已知数字,推理出所有剩余位置的数字,并满足每一行、每一列、每一个粗线九宫格内的数字包含有 1-9 的数字,且不重复。
现在给你一个数独,请你解答出来。每个数独保证有且只有一个解。
输入描述:
输入仅一组数据,共 9 行 9 列,表示初始数独(其中 0 表示数独中的空位)。
输出描述:
输出共 9 行 9 列,表示数独的解。
注意⾏末没有空格。
示例1
输入
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
题解:
直接暴力回溯试探
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int s[9][9];
bool check(int count,int k)
{
int hang=count/9;
int lie=count%9;
for(int i=0;i<9;i++)//检查行列
{
if(s[hang][i]==k)return false;
if(s[i][lie]==k)return false;
}
//检查一小格
hang=hang/3*3;lie=lie/3*3;
for(int i=hang;i<hang+3;i++)
{
for(int j=lie;j<lie+3;j++)
{
if(s[i][j]==k)
return false;
}
}
s[count/9][count%9]=k;
return true;
}
void trystep(int count)
{
if(count==81)
{
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
cout<<s[i][j]<<" ";
}
cout<<endl;
}
return;
}
int hang=count/9;
int lie=count%9;
if(s[hang][lie]==0)
{
for(int i=1;i<=9;i++)
{
if(check(count,i)) //检查1~9
{
trystep(count+1); //可以下一步!!!这里开始用++count然后发现错了,回溯的时候改变了当前count的值。
s[hang][lie]=0; //回溯
}
}
}
else
trystep(count+1); //下一步
}
int main()
{
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
cin>>s[i][j];
trystep(0);
return 0;
}