您的位置:首页 > 其它

Recursion 图像软件中的“填充”函数 @CareerCup

2013-11-27 05:44 369 查看
搞清楚题意后就很简单了,用DFS暴搜即可

package Recursion;

/**
* 原文:

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.

译文:

实现图像处理软件中的“填充”函数,给定一块区域(可以不规则),一个种子点和一种新颜色, 填充这块区域,直到到达这块区域的边界(边界是用这种新颜色画的一条封闭曲线)
*
*/

public class S9_7 {

public static void main(String[] args) {
int N = 10;
Color[][] screen = new Color

;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
screen[i][j] = Color.Black;
}
}
for (int i = 0; i < 100; i++) {
screen[randomInt(N)][randomInt(N)] = Color.Green;
}

PrintScreen(screen);
PaintFill(screen, 2, 2, Color.White);
System.out.println();
PrintScreen(screen);
}

public enum Color {
Black, White, Red, Yellow, Green
}

public static int randomInt(int n) {
return (int) (Math.random() * n);
}

public static void PrintScreen(Color[][] screen) {
for (int i = 0; i < screen.length; i++) {
for (int j = 0; j < screen[0].length; j++) {
System.out.print(PrintColor(screen[i][j]));
}
System.out.println();
}
}

public static String PrintColor(Color 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";
}

// 在本题中要把从(x,y)开始所有相连的旧颜色都替换成新的颜色
public static boolean PaintFill(Color[][] screen, int x, int y, Color newColor) {
if(screen[y][x] == newColor){ // screen[y][x]位置定义的是旧颜色
return false;
}
return PaintFill(screen, x, y, newColor, screen[y][x]);
}

public static boolean PaintFill(Color[][] screen, int x, int y, Color newColor, Color oldColor){
if(x<0 || x>=screen[0].length || y<0 || y>=screen.length){
return false;
}

if(screen[y][x] == oldColor){
screen[y][x] = newColor;
PaintFill(screen, x-1, y, newColor, oldColor); // DFS
PaintFill(screen, x+1, y, newColor, oldColor);
PaintFill(screen, x, y-1, newColor, oldColor);
PaintFill(screen, x, y+1, newColor, oldColor);
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: