Skip to content

Commit ef93525

Browse files
Create Day 11 Flood Fill.cpp
1 parent fe61792 commit ef93525

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Day 11 Flood Fill.cpp

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
PROBLEM:
2+
3+
4+
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
5+
6+
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill"
7+
the image.
8+
9+
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color
10+
as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so
11+
on. Replace the color of all of the aforementioned pixels with the newColor.
12+
At the end, return the modified image.
13+
14+
Example 1:
15+
Input:
16+
image = [[1,1,1],[1,1,0],[1,0,1]]
17+
sr = 1, sc = 1, newColor = 2
18+
Output: [[2,2,2],[2,2,0],[2,0,1]]
19+
20+
Explanation:
21+
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
22+
by a path of the same color as the starting pixel are colored with the new color.
23+
Note the bottom corner is not colored 2, because it is not 4-directionally connected
24+
to the starting pixel.
25+
26+
Note:
27+
The length of image and image[0] will be in the range [1, 50].
28+
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
29+
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
30+
31+
32+
33+
34+
SOLUTION:
35+
36+
37+
class Solution {
38+
private:
39+
40+
void helper(vector<vector<int>>& image,vector<vector<int>>& vis ,int n,int m, int x, int y, int color,int val)
41+
{
42+
if(x>=0 && x<n && y>=0 && y<m && vis[x][y]==false && image[x][y]==val)
43+
{
44+
45+
image[x][y]=color;
46+
vis[x][y]=true;
47+
48+
helper(image,vis,n,m,x+1,y,color,val);
49+
helper(image,vis,n,m,x-1,y,color,val);
50+
helper(image,vis,n,m,x,y+1,color,val);
51+
helper(image,vis,n,m,x,y-1,color,val);
52+
}
53+
}
54+
55+
public:
56+
57+
58+
59+
vector<vector<int>> floodFill(vector<vector<int>>& image, int x, int y,int color) {
60+
61+
int n,m;
62+
n=image.size();
63+
64+
if(n==0)
65+
return image;
66+
67+
m=image[0].size();
68+
69+
if(m==0 || x<0 || x>n || y<0 || y>m )
70+
return image;
71+
72+
73+
vector<vector<int>> vis(n,vector<int>(m,false));
74+
75+
helper(image,vis,n,m,x,y,color,image[x][y]);
76+
77+
78+
return image;
79+
80+
}
81+
};

0 commit comments

Comments
 (0)