If given PaintFill(screen, 2, 2, Color.White), we should have:
Basically we do DFS, the code is shown as following:
public enum Colors{ WHITE, BLACK, GREEN, RED, YELLOW};
public static boolean PaintFillHelper(Colors[][] screen, int row, int col, Colors oldColor, Colors newColor){
if(row < 0 || row >= screen.length || col < 0 || col >= screen.length) return false;//the point we choose is out of bound
if(screen[row][col] == oldColor){
screen[row][col] = newColor;
PaintFillHelper(screen, row+1, col, oldColor, newColor);
PaintFillHelper(screen, row-1, col, oldColor, newColor);
PaintFillHelper(screen, row, col+1, oldColor, newColor);
PaintFillHelper(screen, row, col-1, oldColor, newColor);
}
return true;
}
public static boolean PaintFill(Colors[][] screen, int row, int col, Colors newColor){
if(screen[row][col] == newColor) return false;//the point we choose already have the new color;
else return PaintFillHelper(screen, row, col, screen[row][col], newColor);
}
// Following code is for testing
public static String PrintColor(Colors c) {
switch(c) {
case BLACK:
return "B";
case WHITE:
return "W";
case RED:
return "R";
case YELLOW:
return "Y";
case GREEN:
return "G";
}
return "X";
}
public static void PrintScreen(Colors[][] screen) {
for (int r = 0; r < screen.length; r++) {
for (int c = 0; c < screen[0].length; c++) {
System.out.print(PrintColor(screen[r][c]));
}
System.out.println();
}
}
public static int randomInt(int n) {
return (int) (Math.random() * n);
}
public static void main(String[] args) {
int N = 10;
Colors[][] screen = new Colors[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
screen[i][j] = Colors.BLACK;
}
}
for (int i = 0; i < 100; i++) {
screen[randomInt(N)][randomInt(N)] = Colors.GREEN;
}
PrintScreen(screen);
PaintFill(screen, 0, 0, Colors.WHITE);
System.out.println();
PrintScreen(screen);
}