题目
原文:
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(); } } }