• Source
    1. #include <iostream>
    2.  
    3. namespace {
    4.  
    5. void floodFill( int ** image, int sizeX, int sizeY, int targetColor, int newColor, int x, int y );
    6.  
    7. void floodFillInternal( int ** image, bool ** visited,
    8. int sizeX, int sizeY,
    9. int targetColor, int newColor, int x, int y );
    10. void print(int ** image, int sizeX, int sizeY);
    11.  
    12. }
    13.  
    14. int main(int argc, char** argv)
    15. {
    16. std::cout << "Starting execution" << std::endl;
    17. int sizeX = 3;
    18. int sizeY = 4;
    19. int* image[sizeX];
    20. for(int i = 0 ; i < sizeX ; i++)
    21. {
    22. image[i] = new int[sizeY];
    23. }
    24.  
    25. image[0][2] = 4;
    26. image[1][2] = 4;
    27.  
    28. print(image, sizeX, sizeY);
    29. floodFill(image, sizeX, sizeY, 0, 2, 0, 0 );
    30. print(image, sizeX, sizeY);
    31. std::cout << "Done" << std::endl;
    32.  
    33. for(int i = 0 ; i < sizeX ; i++)
    34. delete[] image[i];
    35. }
    36.  
    37. namespace {
    38.  
    39. void floodFill( int ** image, int sizeX, int sizeY, int targetColor, int newColor, int x, int y )
    40. {
    41. // Check target point is between boundaries
    42. if ( x > sizeX -1 || x < 0 )
    43. return;
    44. if ( y > sizeY-1 || y < 0 )
    45. return;
    46.  
    47. // Initialize visited
    48. bool * visited[ sizeX ];
    49. for( int i = 0 ; i < sizeX ; i++ ) {
    50. visited[i] = new bool[sizeY];
    51. }
    52.  
    53. // Start recursing
    54. floodFillInternal(image, visited, sizeX, sizeY, targetColor, newColor, x, y);
    55.  
    56. // Free the visited structure
    57. for( int i = 0 ; i < sizeX ; i++ ) {
    58. delete[] visited[i];
    59. }
    60. }
    61.  
    62. void floodFillInternal( int ** image, bool ** visited,
    63. int sizeX, int sizeY,
    64. int targetColor, int newColor, int x, int y )
    65. {
    66. // Check target point is between boundaries
    67. if ( x > sizeX -1 || x < 0 )
    68. return;
    69. if ( y > sizeY-1 || y<0 )
    70. return;
    71.  
    72. if ( image[x][y] != targetColor || visited[x][y])
    73. return;
    74.  
    75. image[x][y] = newColor;
    76. visited[x][y] = 1;
    77. floodFillInternal(image, visited, sizeX, sizeY, targetColor, newColor, x+1, y);
    78. floodFillInternal(image, visited, sizeX, sizeY, targetColor, newColor, x-1, y);
    79. floodFillInternal(image, visited, sizeX, sizeY, targetColor, newColor, x, y+1);
    80. floodFillInternal(image, visited, sizeX, sizeY, targetColor, newColor, x, y-1);
    81. }
    82.  
    83. void print(int ** image, int sizeX, int sizeY)
    84. {
    85. std::cout << "[" << std::endl;
    86. for( int i = 0; i < sizeY ; ++i)
    87. {
    88. for(int j = 0 ; j < sizeX ; ++j)
    89. {
    90. std::cout << image[j][i] << " , ";
    91. }
    92. std::cout << std::endl;
    93. }
    94. std::cout << "]" << std::endl;
    95. }
    96. }
    97.