flood8.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. def isValid(screen, m, n, x, y, prevC, newC):
  2. if x < 0 or x >= m or y < 0 or y >= n or screen[x][y] != prevC or screen[x][y] == newC:
  3. return False
  4. return True
  5. # FloodFill function
  6. def floodFill(screen, m, n, x, y, prevC, newC):
  7. queue = []
  8. # Append the position of starting
  9. # pixel of the component
  10. queue.append([x, y])
  11. # Color the pixel with the new color
  12. screen[x][y] = newC
  13. # Define 8 possible directions
  14. directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1)]
  15. # While the queue is not empty i.e. the
  16. # whole component having prevC color
  17. # is not colored with newC color
  18. while queue:
  19. # Dequeue the front node
  20. currPixel = queue.pop()
  21. posX = currPixel[0]
  22. posY = currPixel[1]
  23. # Check if the adjacent pixels are valid
  24. for direction in directions:
  25. newX, newY = posX + direction[0], posY + direction[1]
  26. if isValid(screen, m, n, newX, newY, prevC, newC):
  27. # Color with newC if valid and enqueue
  28. screen[newX][newY] = newC
  29. queue.append([newX, newY])