美文网首页
733. Flood Fill

733. Flood Fill

作者: Super_Alan | 来源:发表于2018-05-02 11:30 被阅读0次

LeetCode Link

改变 image[sr][sc] 的值 to newColor,上下左右若与 image[sr][sc] 的原值相同,则也随之改变。已改变的 pixel 重复上述步骤。

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

private void dfs(int[][] image, int row, int col, int newColor, int oldColor) {
    if (row < 0 || col < 0 || row >= image.length || col >= image[row].length 
            || image[row][col] != oldColor || image[row][col] == newColor) {
        return;
    }
    
    image[row][col] = newColor;
    dfs(image, row - 1, col, newColor, oldColor);
    dfs(image, row + 1, col, newColor, oldColor);
    dfs(image, row, col - 1, newColor, oldColor);
    dfs(image, row, col + 1, newColor, oldColor);
    
}

相关文章

网友评论

      本文标题:733. Flood Fill

      本文链接:https://www.haomeiwen.com/subject/ehnqrftx.html