利用图遍历处理连通分量。
输入是一幅位图,1是黑0是白,不过用十六进制给出,需要做点解码。图中黑像素可能构成几种符号,要求将它们识别输出。
注意需要在图四周加宽度为1的padding,否则可能误把贴着墙的符号的洞眼数量判多。
#include <iostream>
#include <cstring>
#include <set>
#include <vector>
#include <queue>
#include <algorithm>
#define REP(i,n) for(int i=0; i<(n); i++)
using namespace std;
const int maxh = 205, maxw = 55;
char bin[256][5], s[maxw];
int pic[maxh][maxw*4], color[maxh][maxw*4], cnt;
int h, w;
const int dr[] = {-1,0,1,0}, dc[] = {0,1,0,-1};
const char code[] = " WAKJSD";
vector<set<int>> neighbor;
void decode(char c, int row, int col) {
REP(i,4)
pic[row][col+i] = bin[c][i] - '0';
}
void bfs(int row, int col, int clr) {
queue<pair<int,int>> q;
q.push({row,col});
color[row][col] = clr;
while(!q.empty()) {
auto x = q.front(); q.pop();
REP(i,4) {
int r = x.first + dr[i];
int c = x.second + dc[i];
if(r>=0 && r<=h+2 && c>=0 && c<=w*4+2 && pic[r][c]==pic[row][col] && !color[r][c]){
q.push({r,c}); color[r][c] = clr;
}
}
}
}
void lookAround(int row, int col) {
REP(i,4) {
int r = row + dr[i], c = col + dc[i];
if(r>=0 && r<=h && c>=0 && c<=w*4 && !pic[r][c])
neighbor[color[row][col]].insert(color[r][c]);
}
}
int main() {
strcpy(bin['0'], "0000");
strcpy(bin['1'], "0001");
strcpy(bin['2'], "0010");
strcpy(bin['3'], "0011");
strcpy(bin['4'], "0100");
strcpy(bin['5'], "0101");
strcpy(bin['6'], "0110");
strcpy(bin['7'], "0111");
strcpy(bin['8'], "1000");
strcpy(bin['9'], "1001");
strcpy(bin['a'], "1010");
strcpy(bin['b'], "1011");
strcpy(bin['c'], "1100");
strcpy(bin['d'], "1101");
strcpy(bin['e'], "1110");
strcpy(bin['f'], "1111");
int kase = 0;
while(cin >> h >> w && h) {
memset(pic,0,sizeof(pic)); // a padding of background white
REP(i,h) {
cin >> s;
REP(j,w) decode(s[j], i+1, j*4+1);
}
memset(color, 0, sizeof(color)); cnt = 0;
vector<int> cc; // connected component for black pixels
REP(i,h+2) REP(j,w*4+2) {
if(!color[i][j]) {
bfs(i,j,++cnt);
if(pic[i][j]) cc.push_back(cnt);
}
}
neighbor.clear();
neighbor.resize(cnt+1);
REP(i,h+2) REP(j,w*4+2) {
if(pic[i][j]) lookAround(i,j); // get number of neighboring white CCs
}
vector<char> ans;
for(auto x: cc)
ans.push_back(code[neighbor[x].size()]);
sort(ans.begin(), ans.end());
cout << "Case " << ++kase << ": ";
for(auto x: ans) cout << x;
cout << endl;
}
return 0;
}