flood4.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # https://www.geeksforgeeks.org/flood-fill-algorithm/
  2. def isValid(screen, m, n, x, y, prevC, newC):
  3. if x<0 or x>= m\
  4. or y<0 or y>= n or\
  5. screen[x][y]!= prevC\
  6. or screen[x][y]== newC:
  7. return False
  8. return True
  9. # FloodFill function
  10. def floodFill(screen,
  11. m, n, x,
  12. y, prevC, newC):
  13. queue = []
  14. # Append the position of starting
  15. # pixel of the component
  16. queue.append([x, y])
  17. # Color the pixel with the new color
  18. screen[x][y] = newC
  19. # While the queue is not empty i.e. the
  20. # whole component having prevC color
  21. # is not colored with newC color
  22. while queue:
  23. # Dequeue the front node
  24. currPixel = queue.pop()
  25. posX = currPixel[0]
  26. posY = currPixel[1]
  27. # Check if the adjacent
  28. # pixels are valid
  29. if isValid(screen, m, n,
  30. posX + 1, posY,
  31. prevC, newC):
  32. # Color with newC
  33. # if valid and enqueue
  34. screen[posX + 1][posY] = newC
  35. queue.append([posX + 1, posY])
  36. if isValid(screen, m, n,
  37. posX-1, posY,
  38. prevC, newC):
  39. screen[posX-1][posY]= newC
  40. queue.append([posX-1, posY])
  41. if isValid(screen, m, n,
  42. posX, posY + 1,
  43. prevC, newC):
  44. screen[posX][posY + 1]= newC
  45. queue.append([posX, posY + 1])
  46. if isValid(screen, m, n,
  47. posX, posY-1,
  48. prevC, newC):
  49. screen[posX][posY-1]= newC
  50. queue.append([posX, posY-1])