Skip to content

Commit 9f7be86

Browse files
committed
Adding Accepted Solution - Problem - 11 - Flood Fill
1 parent 02a8dd1 commit 9f7be86

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
##==================================
2+
## Leetcode May Challenge
3+
## Username: Vanditg
4+
## Year: 2020
5+
## Problem: 11
6+
## Problem Name: Flood Fill
7+
##===================================
8+
#
9+
#An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
10+
#
11+
#Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
12+
#
13+
#To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
14+
#
15+
#At the end, return the modified image.
16+
#
17+
#Example 1:
18+
#Input:
19+
#image = [[1,1,1],[1,1,0],[1,0,1]]
20+
#sr = 1, sc = 1, newColor = 2
21+
#Output: [[2,2,2],[2,2,0],[2,0,1]]
22+
#Explanation:
23+
#From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
24+
#by a path of the same color as the starting pixel are colored with the new color.
25+
#Note the bottom corner is not colored 2, because it is not 4-directionally connected
26+
#to the starting pixel.
27+
class Solution:
28+
def floodFill(self, image, sr, sc, newColor):
29+
r, c = len(image), len(image[0]) #Initialize r and c
30+
clr = image[sr][sc] #Initialize clr which is the location of the color
31+
if clr == newColor: #Condition-check: If clr is same as newColor
32+
return image #Then we'll not change the color and return that image
33+
def dfs(row, column): #Defining dfs accepts row, and column
34+
if image[row][column] == clr: #Condition-check: If location of that point is same as color
35+
image[row][column] = newColor #Then we change that to newColor
36+
if row >= 1: #Condition-check: If row is greater or equal to 1
37+
dfs(row - 1, column) #Using DFS
38+
if row + 1 < r: #Condition-check: If row + 1 is less than r
39+
dfs(row + 1, column) #Using DFS
40+
if column >= 1: Condition-check: If column is greater or equal to 1
41+
dfs(row, column - 1) #Using DFS
42+
if column + 1 < c: #Condition-check: If column + 1 is less than c
43+
dfs(row, column + 1) #Using DFS
44+
dfs(sr, sc) #Using DFS to change the value to newColor for 4-connected point
45+
return image

0 commit comments

Comments
 (0)