ProgramAlgTrain/20240823/十四届蓝桥比赛/数独填数.cpp

98 lines
2.2 KiB
C++
Raw Normal View History

2024-08-23 14:19:02 +00:00
#include<bits/stdc++.h>
using namespace std;
2024-08-25 05:16:15 +00:00
int m[10][10];
2024-08-30 10:19:48 +00:00
bool h_is_used[10][10],l_is_used[10][10],t_is_used[5][5][10];
2024-08-25 05:16:15 +00:00
2024-08-23 15:14:35 +00:00
#ifdef OI
#define DB(code){code}
2024-08-25 05:16:15 +00:00
#define PV(v){cout<<#v<<" : "<<(v)<<endl;}
2024-08-23 15:14:35 +00:00
#else
#define DB(code)
2024-08-25 05:16:15 +00:00
#define PV(v)
2024-08-23 15:14:35 +00:00
#endif
2024-08-25 05:16:15 +00:00
void dfs(int x,int y);
optional<pair<int,int>> find_next(int x,int y);
2024-08-23 14:19:02 +00:00
int main(){
2024-08-23 15:14:35 +00:00
for(int i=1;i<=9;i++){
2024-08-25 05:16:15 +00:00
string str;
getline(cin,str);
2024-08-23 15:14:35 +00:00
for(int j=1;j<=9;j++){
2024-08-25 05:16:15 +00:00
if(str[j-1]=='.'){
2024-08-23 15:14:35 +00:00
m[i][j]=-1;
}else{
2024-08-25 05:16:15 +00:00
m[i][j]=str[j-1]-'0';
h_is_used[i][m[i][j]]=true;
l_is_used[j][m[i][j]]=true;
t_is_used[i/3+1][j/3+1][m[i][j]]=true;
2024-08-23 15:14:35 +00:00
}
}
}
DB(
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
2024-08-25 05:16:15 +00:00
cout<<m[i][j]<<"\t";
2024-08-23 15:14:35 +00:00
}
cout<<endl;
}
)
2024-08-25 05:16:15 +00:00
auto find = find_next(1, 1);
if(find.has_value()==false){
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
cout<<m[i][j];
}
cout<<endl;
}
exit(0);
}
dfs(find->first, find->second);
2024-08-23 15:14:35 +00:00
}
2024-08-25 05:16:15 +00:00
optional<pair<int,int>> find_next(int x,int y){
for (int j=y+1; j<=9; j++) {
if(m[x][j]==-1){
return make_optional<pair<int,int>>({x,j});
2024-08-23 15:14:35 +00:00
}
}
2024-08-25 05:16:15 +00:00
for(int i=x+1;i<=9;i++){
for(int j=1;j<=9;j++){
if(m[i][j]==-1){
return make_optional<pair<int,int>>({i,j});
}
2024-08-23 15:14:35 +00:00
}
}
2024-08-25 05:16:15 +00:00
return nullopt;
}
void dfs(int x,int y){
DB(PV(x)PV(y)cout<<endl;)
auto find = find_next(x, y);
if(find.has_value()==false){
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
cout<<m[i][j];
}
cout<<endl;
2024-08-23 15:14:35 +00:00
}
2024-08-25 05:16:15 +00:00
exit(0);
2024-08-23 15:14:35 +00:00
}
2024-08-25 05:16:15 +00:00
for(int i=1;i<=9;i++){
if(h_is_used[x][i]||l_is_used[y][i]||t_is_used[x/3+1][y/3+1][i]){
continue;
2024-08-23 15:14:35 +00:00
}
2024-08-25 05:16:15 +00:00
h_is_used[x][i]=true,
l_is_used[y][i]=true,
t_is_used[x/3+1][y/3+1][i]=true;
m[x][y]=i;
2024-08-23 15:14:35 +00:00
2024-08-25 05:16:15 +00:00
dfs(find->first, find->second);
h_is_used[x][i]=false;
l_is_used[y][i]=false;
t_is_used[x/3+1][y/3+1][i]=false;
m[x][y]=-1;
}
}