733. Flood Fill

https://leetcode.com/contest/weekly-contest-60/problems/flood-fill/

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.

contest60的签到题,题意就是类似各种画图软件里的涂色器功能,把容差内相似的颜色涂成一样的。
名字很直白就是flood fill了,直接就用DFS吧,想象一个铁头娃在挖洞,类似word break那种。与word break不同的是它不需要backtracking的时候恢复现场。

class Solution {

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if (image == null || image.length == 0 || sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) {
            return image;
        }
        dfs(image, sr, sc, newColor, new boolean[image.length][image[0].length], image[sr][sc]);
        return image;
    }
    //          111
    //          110
    //          101
    private void dfs(int[][] image, int sr, int sc, int newColor, boolean[][] visited, int originalColor) {
        if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length|| visited[sr][sc] || image[sr][sc]!= originalColor) {
            return;
        }
        //铁头娃
        image[sr][sc] = newColor;
        visited[sr][sc] = true;
        dfs(image, sr - 1, sc, newColor, visited, originalColor);
        dfs(image, sr + 1, sc, newColor, visited, originalColor);
        dfs(image, sr, sc - 1, newColor, visited, originalColor);
        dfs(image, sr, sc + 1, newColor, visited, originalColor);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 灰姑娘的梦想 我试着去穿那粉色的高跟鞋小心翼翼地做着梦中的灰姑娘直到很多年后苦涩都已经尽了独自演绎的悲欢离合都尽了...
    黔北文风阅读 192评论 0 1
  • 算算时间和前任分道扬镳已有四个月。说分道扬镳是因为我和她真的分道了。删掉她的QQ,微信,然后微博取关的时候,就像是...
    Ljoy阅读 274评论 0 0
  • 炭笔.临摹 原画是写意水墨,我用炭笔画,嘿嘿。 今天好冷啊! 前晚熬夜看《绝对是个梦》后缺觉到今天。 老了,不能熬...
    巫落阅读 222评论 0 0
  • 千万不要觉得你是天底下最苦的人,创业的痛苦从古延续到今。 痛苦的根源在于你想快速地改变命运,就得接受命运对你的十倍...
    dec17阅读 264评论 0 0