fork download
  1. #include <stdio.h>
  2.  
  3. #define M 8 // Number of rows
  4. #define N 8 // Number of columns
  5.  
  6. // Function to check if a given pixel is valid
  7. int isValid(int screen[M][N], int x, int y, int oldColor, int newColor) {
  8. // Check if pixel is within bounds, has the old color, and is not already the new color
  9. if (x >= 0 && x < M && y >= 0 && y < N && screen[x][y] == oldColor && screen[x][y] != newColor) {
  10. return 1;
  11. }
  12. return 0;
  13. }
  14.  
  15. // 4-connected recursive flood fill function
  16. void floodFill4Connected(int screen[M][N], int x, int y, int newColor, int oldColor) {
  17. if (!isValid(screen, x, y, oldColor, newColor)) {
  18. return;
  19. }
  20.  
  21. // Replace the color of the current pixel
  22. screen[x][y] = newColor;
  23.  
  24. // Recur for 4 connected neighbours (up, down, left, right)
  25. floodFill4Connected(screen, x + 1, y, newColor, oldColor); // Right
  26. floodFill4Connected(screen, x - 1, y, newColor, oldColor); // Left
  27. floodFill4Connected(screen, x, y + 1, newColor, oldColor); // Down
  28. floodFill4Connected(screen, x, y - 1, newColor, oldColor); // Up
  29. }
  30.  
  31. // Driver code to test the algorithm
  32. int main() {
  33. int screen[M][N] = {
  34. {1, 1, 1, 1, 1, 1, 1, 1},
  35. {1, 1, 1, 1, 1, 1, 0, 0},
  36. {1, 0, 0, 1, 1, 0, 1, 1},
  37. {1, 2, 2, 2, 2, 0, 1, 0},
  38. {1, 1, 1, 2, 2, 0, 1, 0},
  39. {1, 1, 1, 2, 2, 2, 2, 0},
  40. {1, 1, 1, 1, 1, 2, 1, 1},
  41. {1, 1, 1, 1, 1, 2, 2, 1},
  42. };
  43. int x = 4, y = 4, newColor = 3; // Starting position (4, 4) and new color
  44. int oldColor = screen[x][y];
  45.  
  46. printf("Original Screen:\n");
  47. for (int i = 0; i < M; i++) {
  48. for (int j = 0; j < N; j++) {
  49. printf("%d ", screen[i][j]);
  50. }
  51. printf("\n");
  52. }
  53.  
  54. floodFill4Connected(screen, x, y, newColor, oldColor);
  55.  
  56. printf("\nScreen after 4-connected Flood Fill:\n");
  57. for (int i = 0; i < M; i++) {
  58. for (int j = 0; j < N; j++) {
  59. printf("%d ", screen[i][j]);
  60. }
  61. printf("\n");
  62. }
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Original Screen:
1 1 1 1 1 1 1 1 
1 1 1 1 1 1 0 0 
1 0 0 1 1 0 1 1 
1 2 2 2 2 0 1 0 
1 1 1 2 2 0 1 0 
1 1 1 2 2 2 2 0 
1 1 1 1 1 2 1 1 
1 1 1 1 1 2 2 1 

Screen after 4-connected Flood Fill:
1 1 1 1 1 1 1 1 
1 1 1 1 1 1 0 0 
1 0 0 1 1 0 1 1 
1 3 3 3 3 0 1 0 
1 1 1 3 3 0 1 0 
1 1 1 3 3 3 3 0 
1 1 1 1 1 3 1 1 
1 1 1 1 1 3 3 1