AcWing 1613. 數獨簡單版(DFS)
阿新 • • 發佈:2021-02-03
數獨是一種傳統益智遊戲,你需要把一個 9×9 的數獨補充完整,使得圖中每行、每列、每個 3×3 的九宮格內數字 1∼9 均恰好出現一次。
請編寫一個程式填寫數獨。
輸入格式
輸入共 9 行,每行包含一個長度為 9 的字串,用來表示數獨矩陣。
其中的每個字元都是 1∼9 或 .(表示尚未填充)。
輸出格式
輸出補全後的數獨矩陣。
資料保證有唯一解。
輸入樣例:
.2738..1.
.1...6735
.......29
3.5692.8.
.........
.6.1745.3
64.......
9518...7 .
.8..6534.
輸出樣例:
527389416
819426735
436751829
375692184
194538267
268174593
643217958
951843672
782965341
答案:
#include <iostream>
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define INF 0x3f3f3f3f3f3f3f3f
#define rep(i,a,b) for(auto i=a;i<=b;++i)
#define bep(i,a,b) for(auto i=a;i>=b;--i)
#define lowbit(x) x&(-x)
#define PII pair<int,int>
#define PLL pair<ll,ll>
#define PI acos(-1)
#define pb push_back
#define eps 1e-6
const int mod = 1e9 + 7;
const int N = 1e5 + 10;
const int M = 11;
using namespace std;
char s[M][M];
int n=10;
bool DFS(int x,int y){
if(y==9) return 1; /// 如果當前列跳出了最後一列,則直接放回 true
if(x==9) return DFS(0,y+1); /// 如果當前行跳出了最後一行,則返回下一列第零行
if(s[x][y]!='.') return DFS(x+1,y); /// 如果當前行已有數字,直接跳過
bool pos[M]; /// pos 陣列存當前位置 (x, y) 還能填哪些數
memset(pos,0,sizeof(pos));
rep(i,0,n-2){ /// 看一下該列上有哪些數字被填過了
if(s[i][y]>47&&s[i][y]<58){
pos[s[i][y]^48]=1;
}
}
rep(i,0,n-2){ /// 看一下該行上有哪些數字被填過了
if(s[x][i]>47&&s[x][i]<58){
pos[s[x][i]^48]=1;
}
}
int dx=x/3*3; /// 找到當前九宮格的左上角位置
int dy=y/3*3;
rep(i,dx,dx+2){ /// 看一下該九宮格內有哪些數字被填過了
rep(j,dy,dy+2){
if(s[i][j]>47&&s[i][j]<58){
pos[s[i][j]^48]=1;
}
}
}
rep(i,1,n-1){ /// 列舉當前格內能填的所有數字
if(!pos[i]){
s[x][y]=i^48; /// 如果能填,那麼填上,並搜尋下一格
if(DFS(x+1,y)) return 1;
}
}
s[x][y]='.'; /// 如果搜完了所有可填數字,或沒有可填數字,那麼將該格改為未填狀態
return 0; /// 並返回 false
}
void solve(){
rep(i,0,n-2){
cin>>s[i];
}
DFS(0,0);
rep(i,0,n-2){
rep(j,0,n-2){
cout<<s[i][j];
}
cout<<endl;
}
}
int main() {
solve();
return 0;
}