Saturday, November 30, 2013

Floodfill algorithm Java, recursive

import java.util.Arrays;

public class Main
{
public static void main(String[] args)
{
int[][] image = {
{0,0,0},
{1,1,1},
{0,0,0}
};

printImage(image);
floodFill(image, 0, 2, 0, 0);
printImage(image);
}

public static void floodFill(int[][] image, int targetColor,
int newColor, int x, int y)
{
if (image.length < 1 || image[0].length < 1)
return;
if( !checkBoundaries(image, x, y))
return;

boolean visited[][] = new boolean[image.length][image[0].length];

floodFillInternal( image, visited, targetColor, newColor, x, y);

}

private static void floodFillInternal(int[][] image, boolean[][] visited,
  int targetColor, int newColor, int x, int y)
{
if (!checkBoundaries(image, x, y))
return;

if(image[x][y] != targetColor || visited[x][y])
return;

image[x][y] = newColor;
visited[x][y] = true;

floodFillInternal( image, visited, targetColor, newColor, x+1, y);
floodFillInternal( image, visited, targetColor, newColor, x-1, y);
floodFillInternal( image, visited, targetColor, newColor, x, y+1);
floodFillInternal( image, visited, targetColor, newColor, x, y-1);
}

private static boolean checkBoundaries(int[][] image, int x, int y)
{
if ( x >= image.length || x < 0 || y >= image[0].length || y < 0)
return false;
return true;
}

private static void printImage(int[][] image)
{
for(int[] col : image)
System.out.println(Arrays.toString(col));
}
}