原题链接:https://vjudge.net/problem/UVA-11846
分类:回溯法
备注:模拟,水题
注意一下 不填字母的地方一定要是’.’,估计测试数据可能有填不满整个n*n块格子的情况。
#include<bits/stdc++.h>
using namespace std;
int n,k,num[25];
char g[25][25],ans[25][25];
inline char read(){
char ch=getchar();
while(ch==' '||ch=='\n')ch=getchar();
return ch;
}
inline bool check(int x,int y,int w,int h){
int cnt=0;
for(int i=x;i<x+h;i++)
for(int j=y;j<y+w;j++){
if(isalpha(ans[i][j]))return false;
if(isdigit(g[i][j])){
cnt++; if(cnt>1)return false;
if(g[i][j]-'0'!=w*h)return false;
}
}
return cnt==1;
}
bool dfs(int pos,int now){
if(now==k)return true;
while(isalpha(ans[pos/n][pos%n]))pos++;
for(int w=1;w<=9;w++)
for(int h=1;h<=9;h++){
if(w*h>9)continue;
int x=pos/n,y=pos%n;
if(x+h>n||y+w>n)break;
if(check(x,y,w,h)){
for(int i=x;i<x+h;i++)for(int j=y;j<y+w;j++)ans[i][j]='A'+now;
if(dfs(pos+1,now+1))return true;
else for(int i=x;i<x+h;i++)for(int j=y;j<y+w;j++)ans[i][j]='.';
}
}
return false;
}
int main(void){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(~scanf("%d %d",&n,&k)&&n){
int cnt=0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
g[i][j]=read(); ans[i][j]='.';
}
dfs(0,0);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
printf("%c",ans[i][j]);
printf("\n");
}
}
return 0;
}