Implement the “paint fill” function

Implement the “paint fill” function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the surrounding area until you hit a border of that color.

My initial thoughts:

  • Base case: the point is at the border. Do nothing.
  • Recursion: check the up, down, left and right point to see if we can fill in.

My initial codes (solution):

	public static void paintFillRecur(Color[][] screen, 
			int x, int y, Color origin, Color toBeFilled) {
		if (screen[x][y].equals(origin)) {
			screen[x][y] = toBeFilled;

			if (x - 1 >= 0)
				paintFillRecur(screen, x - 1, 
						y, origin, toBeFilled);
			if (x + 1 < screen.length)
				paintFillRecur(screen, x + 1, 
						y, origin, toBeFilled);
			if (y - 1 >= 0)
				paintFillRecur(screen, x, 
						y - 1, origin, toBeFilled);
			if (y + 1 < screen[0].length)
				paintFillRecur(screen, x, 
						y + 1, origin, toBeFilled);
		}
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: