Skip to content

Instantly share code, notes, and snippets.

@stphung
Created May 9, 2011 03:30
Show Gist options
  • Save stphung/962009 to your computer and use it in GitHub Desktop.
Save stphung/962009 to your computer and use it in GitHub Desktop.
Implementation of paint bucket operation using bfs
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class PaintBucket {
public static void main(String[] args) {
int[][] colors = new int[][] {{2,2,0,1},
{1,0,0,0},
{0,0,0,1},
{1,1,1,1}};
int x = 0;
int y = 0;
int fill = 0;
bfs(colors,x,y,fill);
for(int i=0; i<colors.length; i++) {
System.out.println(Arrays.toString(colors[i]));
}
}
public static void bfs(int[][] colors, int r, int c, int fill) {
boolean[][] visited = new boolean[colors.length][colors.length];
for(int i=0; i<visited.length; i++) {
Arrays.fill(visited[i],false);
}
Queue<Location> q = new LinkedList<Location>();
q.add(new Location(r,c));
int replace = colors[r][c];
while (!q.isEmpty()) {
Location loc = q.remove();
visited[loc.r][loc.c] = true;
colors[loc.r][loc.c] = fill;
putIfValid(loc.r+1,loc.c-1,replace,q,visited,colors);
putIfValid(loc.r+1,loc.c,replace,q,visited,colors);
putIfValid(loc.r+1,loc.c+1,replace,q,visited,colors);
putIfValid(loc.r-1,loc.c-1,replace,q,visited,colors);
putIfValid(loc.r-1,loc.c,replace,q,visited,colors);
putIfValid(loc.r-1,loc.c+1,replace,q,visited,colors);
putIfValid(loc.r,loc.c+1,replace,q,visited,colors);
putIfValid(loc.r,loc.c-1,replace,q,visited,colors);
}
}
public static void putIfValid(int r, int c, int replace, Queue<Location> q, boolean[][] visited, int[][] colors) {
if (valid(r,c,replace,visited,colors)) {
q.add(new Location(r,c));
}
}
public static boolean valid(int r, int c, int replace, boolean[][] visited, int[][] colors) {
return r >= 0 && r < visited.length &&
c >= 0 && c < visited.length &&
!visited[r][c] && colors[r][c] == replace;
}
private static class Location {
private final int r;
private final int c;
public Location(int r, int c) {
this.r = r;
this.c = c;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment