|
| 1 | +package com.thealgorithms.others; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.Queue; |
| 5 | + |
| 6 | +public class IterativeFloodFill { |
| 7 | + |
| 8 | + /** |
| 9 | + * Represents a point in 2D space with integer coordinates. |
| 10 | + */ |
| 11 | + private static class Point { |
| 12 | + public final int x; |
| 13 | + public final int y; |
| 14 | + |
| 15 | + public Point(final int x, final int y) { |
| 16 | + this.x = x; |
| 17 | + this.y = y; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Checks if a pixel should be skipped during flood fill operation. |
| 23 | + * |
| 24 | + * @param image The image to get boundaries |
| 25 | + * @param x The x co-ordinate of pixel to check |
| 26 | + * @param y The y co-ordinate of pixel to check |
| 27 | + * @param oldColor The old color which is to be replaced in the image |
| 28 | + * @return {@code true} if pixel should be skipped, else {@code false} |
| 29 | + */ |
| 30 | + private static boolean shouldSkipPixel(final int[][] image, final int x, final int y, final int oldColor) { |
| 31 | + |
| 32 | + if (x < 0 || x >= image.length || |
| 33 | + y < 0 || y >= image[0].length || |
| 34 | + image[x][y] != oldColor) { |
| 35 | + return true; |
| 36 | + } |
| 37 | + |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Iteratively fill the 2D image with new color |
| 43 | + * |
| 44 | + * @param image The image to be filled |
| 45 | + * @param x The x co-ordinate at which color is to be filled |
| 46 | + * @param y The y co-ordinate at which color is to be filled |
| 47 | + * @param newColor The new color which to be filled in the image |
| 48 | + * @param oldColor The old color which is to be replaced in the image |
| 49 | + */ |
| 50 | + public static void floodFill(final int[][] image, final int x, final int y, final int newColor, final int oldColor) { |
| 51 | + if (image.length == 0 || image[0].length == 0 || newColor == oldColor || shouldSkipPixel(image, x, y, oldColor)) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + Queue<Point> queue = new LinkedList<>(); |
| 56 | + queue.add(new Point(x, y)); |
| 57 | + |
| 58 | + int[] dx = {0, 0, -1, 1, 1, -1, 1, -1}; |
| 59 | + int[] dy = {-1, 1, 0, 0, -1, 1, 1, -1}; |
| 60 | + |
| 61 | + |
| 62 | + while (!queue.isEmpty()) { |
| 63 | + Point currPoint = queue.poll(); |
| 64 | + |
| 65 | + if (shouldSkipPixel(image, currPoint.x, currPoint.y, oldColor)) { |
| 66 | + continue; |
| 67 | + } |
| 68 | + |
| 69 | + image[currPoint.x][currPoint.y] = newColor; |
| 70 | + |
| 71 | + for (int i = 0; i < 8; i++) { |
| 72 | + int curX = currPoint.x + dx[i]; |
| 73 | + int curY = currPoint.y + dy[i]; |
| 74 | + |
| 75 | + if (!shouldSkipPixel(image, curX, curY, oldColor)) { |
| 76 | + queue.add(new Point(curX, curY)); |
| 77 | + } |
| 78 | + |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments