当输入的n的值小于0的时候,首先将n的值取反,然后读取相应的数值,对于读取的数,按照不断模5来找出应该所在的数组中矩形区域的位置,然后将确定好的矩形区域全部置为1即可。当输入的n的值大于0的时候,首先读取相应的矩阵,递归判断,首先判断矩阵中是否所有的元素值均为1,如果均为1,就按照递归得到的字符串来求出相应的数值,否则将当前的矩阵分为4个部分,分别递归地处理判断即可。具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
using namespace std;
int n;
int area[70][70];
vector<int> result;
vector<int> rec;
int data;
int getData(string s){
int res = 0;
for (int i = 0; i < s.size(); i++){
res = res * 5 + (s[i]-'0');
}
return res;
}
void getRes(int row,int col,int width,string s){
if (width == 0) return;
int temp = 0;
for (int i = row; i < row + width; i++){
for (int j = col; j < col + width; j++){
temp += area[i][j];
}
}
if (temp == width*width) result.push_back(getData(s));
else{
getRes(row, col, width / 2, "1" + s);
getRes(row, col + width / 2, width / 2, "2" + s);
getRes(row + width / 2, col, width / 2, "3" + s);
getRes(row + width / 2, col + width / 2, width / 2, "4" + s);
}
}
void process(int row,int col,int width){
while (data % 5){
width = width / 2;
switch (data % 5){
case 1:break;
case 2:col += width;
break;
case 3:row += width;
break;
case 4:row += width;
col += width;
break;
}
data = data / 5;
}
for (int i = row; i < row + width; i++){
for (int j = col; j < col + width; j++) area[i][j] = 1;
}
}
int main(){
int Case = 0;
while (cin >> n&&n){
memset(area,0,sizeof(70));
if (Case) cout << endl;
Case++;
if (n < 0){
n = -n;
while (cin>>data&&data!=-1){
process(0, 0, n);
}
cout << "Image " << Case << endl;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (area[i][j] == 0) cout << '.';
else cout << '*';
}
cout << endl;
}
}
else{//n>0
for (int i = 0; i < n; i++){
string s;
cin >> s;
for (int j = 0; j < n; j++){
area[i][j] = s[j] - '0';
}
}
result.clear();
getRes(0, 0, n, "");
cout << "Image " << Case << endl;
sort(result.begin(),result.end());
if (result.size()){
for (int i = 0; i < result.size();){
cout << result[i];
i++;
if (i % 12 == 0 && i < result.size()) cout << endl;
else if (i < result.size()) cout << ' ';
}
cout << endl;
cout << "Total number of black nodes = " << result.size() << endl;
}
else{
cout << "Total number of black nodes = 0" << endl;
}
}
}
return 0;
}