733.图像渲染

733.图像渲染

image-20200816235209946

题解

​ 后续的操作类似,使用递归算法,深度优先搜索。注意要保留原有颜色来递归。

class Solution {
    
    
    int[] dx = {
    
    1, 0, 0, -1};
    int[] dy = {
    
    0, 1, -1, 0};

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
    
    
        int currColor = image[sr][sc];
        if (currColor != newColor) {
    
    
            dfs(image, sr, sc, currColor, newColor);
        }
        return image;
    }

    public void dfs(int[][] image, int x, int y, int color, int newColor) {
    
    
        if (image[x][y] == color) {
    
    
            image[x][y] = newColor;
            for (int i = 0; i < 4; i++) {
    
    
                int mx = x + dx[i], my = y + dy[i];
                if (mx >= 0 && mx < image.length && my >= 0 && my < image[0].length) {
    
    
                    dfs(image, mx, my, color, newColor);
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Rush6666/article/details/108046737