#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 25;
char matrix[maxn][maxn], ans[maxn][maxn];
int n, k;
int GetGroupCnt(int l, int t, int r, int d) {
int cnt = 0,ret = 0;
for (int i = l; i <= r; i++) {
for (int j = t; j <= d; j++) {
if (isdigit(matrix[i][j])){
ret = matrix[i][j] - '0';
if (++cnt > 1) return -cnt;
}
}
}
return ret;
}
void FillAns(int l, int t, int r, int d,char value) {
for (int i = l; i <= r; i++) {
for (int j = t; j <= d; j++) {
ans[i][j] = value;
}
}
}
bool dfs(int index, char id) {
//index一维的下标转化为二维下标 找空闲的
while (ans[index / n][index % n] != '.') ++index;
if (index == n * n) return true;
//确定左上角坐标 x y
int lx = index / n, ly = index % n,rBound = n,isover = 0;
//找右下角坐标
for (int rx = lx; rx < n; rx++) {
for (int ry = ly; ry < rBound; ry++) {
//向右扩展失败 当前已被填充 收缩右部
if (ans[rx][ry] != '.') { rBound = ry;break; }
//计算容量的人数
int tot = (ry - ly + 1) * (rx - lx + 1);
//太大了 人家不想要
if (tot > 9) { rBound = ry; break; }
//查看当前矩形局域是否只有一个小组且容量够
int cnt = GetGroupCnt(lx, ly, rx, ry);
//找到多个小组收缩 或者容量大了
if (cnt < 0 || (cnt > 0 && cnt < tot )) {
//收缩右部
rBound = ry;
break;
}
//容量不够 继续扩展 或者一个都没有
if(cnt > tot || cnt == 0) continue;
//尝试填充
FillAns(lx, ly, rx, ry, id);
//能够找到解决方案就不回溯
if (dfs(index, id + 1)) return true;
//不行啊
FillAns(lx, ly, rx, ry, '.');
}
}
return false;
}
int main()
{
while (cin >> n >> k && n && k) {
memset(ans, '.', sizeof(ans));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
dfs(0, 'A');
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << ans[i][j];
}
cout << endl;
}
}
return 0;
}
习题7-16(uva-11846)
最新推荐文章于 2021-07-01 11:56:40 发布