fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #include <iostream>
  4. #include <vector>
  5. using namespace std;
  6.  
  7. void dfs(vector<vector<int>>& img, int x,
  8. int y, int oldColor, int newColor) {
  9.  
  10. if (x < 0 || x >= img.size() ||
  11. y < 0 || y >= img[0].size() || img[x][y] != oldColor) {
  12. return;
  13. }
  14.  
  15. // Update the color of the current pixel
  16. img[x][y] = newColor;
  17.  
  18. // Recursively visit all 4 connected neighbors
  19. dfs(img, x + 1, y, oldColor, newColor);
  20. dfs(img, x - 1, y, oldColor, newColor);
  21. dfs(img, x, y + 1, oldColor, newColor);
  22. dfs(img, x, y - 1, oldColor, newColor);
  23. }
  24.  
  25. vector<vector<int>> floodFill(vector<vector<int>>& img, int sr,
  26. int sc, int newColor) {
  27.  
  28. // If the starting pixel already has the new color,
  29. // no changes are needed
  30. if (img[sr][sc] == newColor) {
  31. return img;
  32. }
  33.  
  34. // Call DFS to start filling from the source pixel
  35. // Store original color
  36. int oldColor = img[sr][sc];
  37. dfs(img, sr, sc, oldColor, newColor);
  38.  
  39. return img;
  40. }
  41.  
  42. int main() {
  43. vector<vector<int>> img = {
  44. {1, 1, 1, 0},
  45. {0, 1, 1, 1},
  46. {1, 0, 1, 1}
  47. };
  48.  
  49. int sr = 1, sc = 2;
  50.  
  51. int newColor = 2;
  52.  
  53. vector<vector<int>> result = floodFill(img, sr, sc, newColor);
  54.  
  55. for (auto& row : result) {
  56. for (auto& pixel : row) {
  57. cout << pixel << " ";
  58. }
  59. }
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
2 2 2 0 0 2 2 2 1 0 2 2