Java

  • import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    
    /**
    
     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.
    
     Note:
    
     The length of image and image[0] will be in the range [1, 50].
     The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
     The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
    
     */
    public class Flood_Fill {
    
        public static void main(String[] args) {
            Flood_Fill out = new Flood_Fill();
            Solution s = out.new Solution();
    
            System.out.println(Arrays.deepToString(s.floodFill(new int[][]{ {0,0,0}, {0,1,0} }, 1, 0, 2)));
        }
    
        class Solution {
    
            HashMap<Integer, List<Integer>> isVisited = new HashMap<>();
    
            public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
    
                if (image == null || image[0] == null) {
                    return image;
                }
    
                dfs(image, sr, sc, newColor, image[sr][sc]);
    
                return image;
            }
    
            // corner case: [[0,0,0],[0,1,1]], set [1,1] new color 1 will overlap existing ones
            public void dfs(int[][] image, int i, int j, int newColor, int originalColor) {
    
                if (i < 0 || i >= image.length || j < 0 || j >= image[0].length || image[i][j] != originalColor || (isVisited.containsKey(i) && isVisited.get(i).contains(j))) {
                    return;
                }
    
                image[i][j] = newColor;
    
                if (isVisited.containsKey(i)) {
                    isVisited.get(i).add(j);
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(j);
                    isVisited.put(i, list);
                }
    
                dfs(image, i + 1, j, newColor, originalColor);
                dfs(image, i - 1, j, newColor, originalColor);
                dfs(image, i, j + 1, newColor, originalColor);
                dfs(image, i, j - 1, newColor, originalColor);
            }
        }
    }
    
  • // OJ: https://leetcode.com/problems/flood-fill/
    // Time: O(MN)
    // Space: O(MN)
    class Solution {
    private:
        int M, N, color, dirs[4][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };
        void dfs(vector<vector<int>>& image, int sr, int sc, int newColor) {
            if (sr < 0 || sr >= M || sc < 0 || sc >= N || image[sr][sc] != color) return;
            image[sr][sc] = newColor;
            for (auto dir : dirs) {
                dfs(image, sr + dir[0], sc + dir[1], newColor);
            }
        }
    public:
        vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
            color = image[sr][sc];
            if (color == newColor) return image;
            M = image.size();
            N = image[0].size();
            dfs(image, sr, sc, newColor);
            return image;
        }
    };
    
  • class Solution(object):
        def floodFill(self, image, sr, sc, newColor):
            """
            :type image: List[List[int]]
            :type sr: int
            :type sc: int
            :type newColor: int
            :rtype: List[List[int]]
            """
            SR, SC = len(image), len(image[0])
            color = image[sr][sc]
            if color == newColor: return image
            def dfs(r, c):
                if image[r][c] == color:
                    image[r][c] = newColor
                    if r >= 1: dfs(r - 1, c)
                    if r < SR - 1: dfs(r + 1, c)
                    if c >= 1: dfs(r, c - 1)
                    if c < SC - 1: dfs(r, c + 1)
            dfs(sr, sc)
            return image
    

Java

  • class Solution {
        public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
            int prevColor = image[sr][sc];
            if (newColor == prevColor)
                return image;
            int rows = image.length, columns = image[0].length;
            int[][] newImage = new int[rows][columns];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++)
                    newImage[i][j] = image[i][j];
            }
            newImage[sr][sc] = newColor;
            Queue<int[]> queue = new LinkedList<int[]>();
            queue.offer(new int[]{sr, sc});
            int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
            while (!queue.isEmpty()) {
                int[] pixel = queue.poll();
                int row = pixel[0], column = pixel[1];
                for (int[] direction : directions) {
                    int newRow = row + direction[0], newColumn = column + direction[1];
                    if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && newImage[newRow][newColumn] == prevColor) {
                        newImage[newRow][newColumn] = newColor;
                        queue.offer(new int[]{newRow, newColumn});
                    }
                }
            }
            return newImage;
        }
    }
    
  • // OJ: https://leetcode.com/problems/flood-fill/
    // Time: O(MN)
    // Space: O(MN)
    class Solution {
    private:
        int M, N, color, dirs[4][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };
        void dfs(vector<vector<int>>& image, int sr, int sc, int newColor) {
            if (sr < 0 || sr >= M || sc < 0 || sc >= N || image[sr][sc] != color) return;
            image[sr][sc] = newColor;
            for (auto dir : dirs) {
                dfs(image, sr + dir[0], sc + dir[1], newColor);
            }
        }
    public:
        vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
            color = image[sr][sc];
            if (color == newColor) return image;
            M = image.size();
            N = image[0].size();
            dfs(image, sr, sc, newColor);
            return image;
        }
    };
    
  • class Solution(object):
        def floodFill(self, image, sr, sc, newColor):
            """
            :type image: List[List[int]]
            :type sr: int
            :type sc: int
            :type newColor: int
            :rtype: List[List[int]]
            """
            SR, SC = len(image), len(image[0])
            color = image[sr][sc]
            if color == newColor: return image
            def dfs(r, c):
                if image[r][c] == color:
                    image[r][c] = newColor
                    if r >= 1: dfs(r - 1, c)
                    if r < SR - 1: dfs(r + 1, c)
                    if c >= 1: dfs(r, c - 1)
                    if c < SC - 1: dfs(r, c + 1)
            dfs(sr, sc)
            return image
    

All Problems

All Solutions