Skip to content

Commit 469d0f6

Browse files
authored
Update 733. Flood Fill
1 parent a687594 commit 469d0f6

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Graph/733. Flood Fill

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,58 @@ public:
3535
return ans ;
3636
}
3737
};
38+
39+
40+
41+
42+
43+
44+
45+
46+
47+
--------------------------------------------------other alogrithm ------------------------------------geeksforgeeks
48+
49+
//{ Driver Code Starts
50+
#include<bits/stdc++.h>
51+
using namespace std;
52+
53+
// } Driver Code Ends
54+
class Solution {
55+
private:
56+
57+
void dfs(int row ,int col , vector<vector<int>>&ans ,vector<vector<int>>&image ,
58+
int newColor, int delRow[] ,int delCol[] , int initColor )
59+
{
60+
ans[row][col] = newColor ;
61+
int n = image.size();
62+
int m = image[0].size();
63+
64+
// there are exactly 4 neighbours
65+
for(int i = 0 ; i < 4 ; i++)
66+
{
67+
int nRow = row + delRow[i];
68+
int nCol = col + delCol[i];
69+
70+
// check for valid coordinate
71+
if(nRow >= 0 && nRow < n && nCol >= 0 && nCol < m && ans[nRow][nCol] != newColor &&
72+
image[nRow][nCol] == initColor)
73+
{
74+
dfs(nRow , nCol , ans , image , newColor ,delRow , delCol , initColor);
75+
}
76+
}
77+
}
78+
public:
79+
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
80+
81+
// get initial color
82+
int initColor = image[sr][sc];
83+
vector<vector<int>> ans = image ;
84+
// delta row and delta column for neighbours
85+
int delRow[] = {-1 , 0 , 1 , 0};
86+
int delCol[] = {0 , 1 , 0 , -1};
87+
dfs(sr , sc , ans , image , newColor ,delRow , delCol , initColor);
88+
return ans ;
89+
90+
91+
}
92+
};

0 commit comments

Comments
 (0)