#include <iostream>
using namespace std;
const int w = 5, h = 5;
int input[w][h] = {{1,0,0,0,1},
{1,1,0,1,1},
{0,1,0,0,1},
{1,1,1,1,0},
{0,0,0,1,0}};
int component[w*h];
void doUnion(int a, int b)
{
// get the root component of a and b, and set the one's parent to the other
while (component[a] != a)
a = component[a];
while (component[b] != b)
b = component[b];
component[b] = a;
}
void unionCoords(int x, int y, int x2, int y2)
{
if (y2 < h && x2 < w && input[x][y] && input[x2][y2])
doUnion(x*h + y, x2*h + y2);
}
int main()
{
// set up input
for (int i = 0; i < w*h; i++)
component[i] = i;
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
{
unionCoords(x, y, x+1, y);
unionCoords(x, y, x, y+1);
}
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
if (input[x][y] == 0)
{
cout << ' ';
continue;
}
int c = x*h + y;
while (component[c] != c) c = component[c];
cout << (char)('a'+c);
}
cout << "\n";
}
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwpjb25zdCBpbnQgdyA9IDUsIGggPSA1OwppbnQgaW5wdXRbd11baF0gPSAge3sxLDAsMCwwLDF9LAoJCQkJCXsxLDEsMCwxLDF9LAoJCQkJCXswLDEsMCwwLDF9LAoJCQkJCXsxLDEsMSwxLDB9LAoJCQkJCXswLDAsMCwxLDB9fTsKaW50IGNvbXBvbmVudFt3KmhdOwp2b2lkIGRvVW5pb24oaW50IGEsIGludCBiKQp7CiAgLy8gZ2V0IHRoZSByb290IGNvbXBvbmVudCBvZiBhIGFuZCBiLCBhbmQgc2V0IHRoZSBvbmUncyBwYXJlbnQgdG8gdGhlIG90aGVyCiAgd2hpbGUgKGNvbXBvbmVudFthXSAhPSBhKQogICAgYSA9IGNvbXBvbmVudFthXTsKICB3aGlsZSAoY29tcG9uZW50W2JdICE9IGIpCiAgICBiID0gY29tcG9uZW50W2JdOwogIGNvbXBvbmVudFtiXSA9IGE7Cn0KCnZvaWQgdW5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