Facebook Interview Question
Software Engineer / DevelopersCountry: United States
Java implementation. No need for "visited" set because when we color a pixel with the new color we know we've already visited it.
private static void fill(int r, int c, int newColor, int[][] mat) {
int rows = mat.length;
if (rows == 0) {
return;
}
int cols = mat[0].length;
int oldColor = mat[r][c];
if (oldColor == newColor) {
return;
}
Queue<Integer> queue = new ArrayDeque<>();
queue.add(r * cols + c);
while (!queue.isEmpty()) {
int pos = queue.poll();
int currR = pos / cols;
int currC = pos % cols;
if (mat[currR][currC] != oldColor) {
continue;
}
mat[currR][currC] = newColor;
if (currC > 0)
queue.add(currR * cols + currC - 1);
if (currC < cols - 1)
queue.add(currR * cols + currC + 1);
if (currR > 0)
queue.add((currR - 1) * cols + currC);
if (currR < rows - 1)
queue.add((currR + 1) * cols + currC);
}
}
FloodFill(Pixel p, Color curr, Color new)
- William Borges September 26, 2011{
if Color(p) != curr then return
Q.Add(p); // Q is a queue that stores pixels
while Q is not empty do
{
p = Q.getFirst();
if Color(p) == curr then set color(p) = new;
Q.Add(p.rightPixel());
Q.Add(p.leftPixel());
Q.Add(p.topPixel());
Q.Add(p.bottomPixel());
}
return;
}