fork(61) download
  1. #include <iostream>
  2. using namespace std;
  3. const int w = 5, h = 5;
  4. int input[w][h] = {{1,0,0,0,1},
  5. {1,1,0,1,1},
  6. {0,1,0,0,1},
  7. {1,1,1,1,0},
  8. {0,0,0,1,0}};
  9. int component[w*h];
  10. void doUnion(int a, int b)
  11. {
  12. // get the root component of a and b, and set the one's parent to the other
  13. while (component[a] != a)
  14. a = component[a];
  15. while (component[b] != b)
  16. b = component[b];
  17. component[b] = a;
  18. }
  19.  
  20. void unionCoords(int x, int y, int x2, int y2)
  21. {
  22. if (y2 < h && x2 < w && input[x][y] && input[x2][y2])
  23. doUnion(x*h + y, x2*h + y2);
  24. }
  25.  
  26. int main()
  27. {
  28. // set up input
  29. for (int i = 0; i < w*h; i++)
  30. component[i] = i;
  31. for (int x = 0; x < w; x++)
  32. for (int y = 0; y < h; y++)
  33. {
  34. unionCoords(x, y, x+1, y);
  35. unionCoords(x, y, x, y+1);
  36. }
  37.  
  38. for (int x = 0; x < w; x++)
  39. {
  40. for (int y = 0; y < h; y++)
  41. {
  42. if (input[x][y] == 0)
  43. {
  44. cout << ' ';
  45. continue;
  46. }
  47. int c = x*h + y;
  48. while (component[c] != c) c = component[c];
  49. cout << (char)('a'+c);
  50. }
  51. cout << "\n";
  52. }
  53. }
  54.  
  55.  
Success #stdin #stdout 0s 15224KB
stdin
Standard input is empty
stdout
p   i
pp ii
 p  i
pppp 
   p