Cracking the coding interview--Q8.6

题目

原文:

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.

译文:

实现类似图像处理软件的“填充”函数,也就是说,给定一个区域(表示为一个二维数组的颜色),一个点,和一个新的颜色,填写周边地区直到你遇到一个边境的颜色。

解答

此题若没学过图像处理,刚开始有点不好理解,也不清楚要实现怎样效果,其实就是给予一个点,然后以此为中心,向上下左右四个方向调用递归函数,进行着色,遇到边界了,就停止着色。把问题简单化,把图片想象成全为0的矩阵,着色就表示为将某一区域的0变为1,代码如下:

public static int[][] picture=new int[9][9];
	public static int[] borderLeftUpCorner = new int[]{1,2};
	public static int[] borderRightDownCorner=new int[]{6,6};
	public static void paint(int x,int y){
		if(x<0||x>picture.length||y<0||y>picture[0].length)
			return;
	
		
		if(x>=borderLeftUpCorner[0]&&x<=borderRightDownCorner[0]
		  &&y>=borderLeftUpCorner[1]&&y<=borderRightDownCorner[1]){
			if(picture[x][y]==0){
				picture[x][y]=1;
				paint(x+1,y);
				paint(x-1,y);
				paint(x,y+1);
				paint(x,y-1);
			}
		
		}
	
	}

完整代码如下:

class Q8_6{
	public static int[][] picture=new int[9][9];
	public static int[] borderLeftUpCorner=new int[]{1,2};
	public static int[] borderRightDownCorner=new int[]{6,6};
	
	public static void paint(int x,int y){
		if(x<0||x>picture.length||y<0||y>picture.length)
			return;
		if(x>=borderLeftUpCorner[0]&&x<=borderRightDownCorner[0]
			&&y>=borderLeftUpCorner[1]&&y<=borderRightDownCorner[1]){
			if(picture[x][y]==0){
				picture[x][y]=1;
				paint(x+1,y);
				paint(x-1,y);
				paint(x,y+1);
				paint(x,y-1);
			}
		}
	}
	
	public static void main(String[] arg){
		int x=3,y=4;
		paint(x,y);	
		for(int i=0;i<picture.length;i++){
			for(int j=0;j<picture[0].length;j++){
				System.out.print(picture[i][j]);
			}
			System.out.println();
		}
	}
}

---EOF---

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值