程序员面试金典-面试题 08.10. 颜色填充

题目:

颜色填充。编写函数,实现许多图片编辑软件都支持的“颜色填充”功能。给定一个屏幕(以二维数组表示,元素为颜色值)、一个点和一个新的颜色值,将新颜色值填入这个点的周围区域,直到原来的颜色值全都改变。

示例1:

输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出:[[2,2,2],[2,2,0],[2,0,1]]
解释:
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
说明:

image 和 image[0] 的长度在范围 [1, 50] 内。
给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。
image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。

分析:

dfs搜索,不过注意的是,这个填充是在原来的数字相连所填充的,所以除边界条件外,还需要判断新填充位置的颜色是不是原来的颜色,如果不是就返回。

程序:

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        m = image.length;
        n = image[0].length;
        int[][] visit = new int [m][n];
        int oldColor = image[sr][sc];
        dfs(image, visit, sr, sc, newColor, oldColor);
        return image;
    }
    private void dfs(int[][] image, int[][] visit, int x, int y, int newColor, int oldColor){
        if(x < 0 || x >= m || y < 0 || y >= n || visit[x][y] == 1 || image[x][y] != oldColor)
            return;
        image[x][y] = newColor;
        visit[x][y] = 1;
        for(int i = 0; i < 4; ++i){
            int nx = x + move[i][0];
            int ny = y + move[i][1];
            dfs(image, visit, nx, ny, newColor, oldColor);
        }
    }
    private int m;
    private int n;
    private int[][] move = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
}

 

posted @ 2020-03-11 14:12  silentteller  阅读(260)  评论(0编辑  收藏  举报