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

搞清楚题意后就很简单了,用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[N][N];
		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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值