此题是十六进制转为二进制+DFS,通过搜索图像中有几个被隔绝的白“洞”来判断是哪个文字。这里考虑一个问题,图像最外面的白色空间怎么办?想到先提前把图像外层的白色空间搜索完毕,从而搜索时只会考虑被包在中间的白色。但是如果黑色占据了边缘,隔绝了外层的白色呢?所以在这里我在整个图像的外面再加一层白色,从而使整个图像的外部白色连成一起。输出时,由于按照字典序输出,可以考虑使用vector,每次判断出一个文字时加入,最后在输出前调用一次sort()即可。
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
using namespace std;
const int maxn = 205;
char dict[16][5] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };
char alpha[] = { 'W', 'A', 'K', 'J', 'S', 'D' };
int a[maxn][maxn];
int n, m;
int dirx[] = { 0, 0, -1, 1 }, diry[] = { -1, 1, 0, 0 };
int cur;
bool isin(int r, int c){
if (r<0 || c<0 || r > n+1 || c > m+1)
return false;
return true;
}
void dfs1(int r, int c){//遍历白色 0
if (!isin(r, c) || a[r][c] != 0)
return;
a[r][c] = 3;
for (int i = 0; i < 4; i++)
dfs1(r + dirx[i], c + diry[i]);
}
void dfs2(int r, int c){
if (!isin(r, c) || a[r][c] != 1)
return;
a[r][c] = 2;
for (int i = 0; i < 4; i++){
int dr = r + dirx[i], dc = c + diry[i];
if (!isin(dr, dc))
continue;
if (a[dr][dc] == 0){
cur++;
dfs1(dr, dc);
}
else if (a[dr][dc] == 1)
dfs2(dr, dc);
}
}
int main()
{
int kase = 0;
while (cin >> n >> m && n && m){
++kase;
vector<char> v;
memset(a, 0, sizeof(a));
for (int i = 1; i <= n; i++){
int k = 1;
for (int j = 1; j <= m; j++){
char c;
cin >> c;
int t;
if (c >= '0'&&c <= '9')
t = c - '0';
else
t = c - 'a' + 10;
for (int p = 0; p < 4; p++)
a[i][k++] = dict[t][p] - '0';
}
}
m = 4 * m;
dfs1(0, 0);
for (int i = 1; i <= n; i++){
for (int j = 1; j <= m; j++){
if (a[i][j] == 1){
cur = 0;
dfs2(i, j);
v.push_back(alpha[cur]);
}
}
}
sort(v.begin(), v.end());
printf("Case %d: ", kase);
for (int i = 0; i < v.size(); i++)
cout << v[i];
cout << endl;
}
return 0;
}