Advertisement
rishu110067

Untitled

Feb 3rd, 2022
978
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. class Solution:
  2.     def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
  3.        
  4.         def bfs(x,y):
  5.             q = deque()
  6.             q.append((x,y))
  7.             oldcolor = image[x][y]
  8.             image[x][y] = newColor
  9.            
  10.             if newColor == oldcolor:
  11.                return
  12.            
  13.             while len(q) > 0:
  14.                 (r,c) = q.popleft()
  15.                 for row,col in neighbors(r,c):
  16.                     if image[row][col] == oldcolor:
  17.                         q.append((row,col))
  18.                         image[row][col]= newColor
  19.                        
  20.         def neighbors(row,col):
  21.             result=[]
  22.             if row-1 >= 0:
  23.                 result.append((row-1,col))
  24.             if col-1 >=0:
  25.                 result.append((row,col-1))
  26.             if row+1 < len(image):
  27.                 result.append((row+1,col))
  28.             if col+1 < len(image[0]):
  29.                 result.append((row,col+1))
  30.             return result
  31.        
  32.         bfs(sr,sc)
  33.         return image
  34.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement