May 01, 2022

733. Flood Fill

733. Flood Fill

Solution 1. DFS

Time = O(mn), space = O(mn) - size of the call stack

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if (image[sr][sc] == newColor) {
            return image;
        }
        int color = image[sr][sc];
        dfs(image, sr, sc, color, newColor);
        return image;
    }
    
    private void dfs(int[][] image, int sr, int sc, int color, int newColor) {
        if (sr < 0 || sc < 0 || sr > image.length - 1 || sc > image[0].length - 1 || image[sr][sc] != color) {
            return;
        }
        image[sr][sc] = newColor;
        dfs(image, sr - 1, sc, color, newColor);
        dfs(image, sr + 1, sc, color, newColor);
        dfs(image, sr, sc - 1, color, newColor);
        dfs(image, sr, sc + 1, color, newColor);
    }
}

Solution2. BFS

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        if (image[sr][sc] == color) {
            return image;
        }
        Queue<int[]> queue = new LinkedList<>();
        int startingColor = image[sr][sc];
        image[sr][sc] = color;
        queue.offer(new int[]{sr, sc});
        int[][] dirs = `{`{-1, 0}, {1, 0}, {0, -1}, {0, 1}`}`;
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            for (int[] dir : dirs) {
                int row = cur[0] + dir[0];
                int col = cur[1] + dir[1];
                if (row < 0 || col < 0 || row > image.length - 1 || col > image[0].length - 1) {
                    continue;
                }
                if (image[row][col] == startingColor) {
                    image[row][col] = color;
                    queue.offer(new int[]{row, col});
                }   
            }
        }
        return image;
    }
}
comments powered by Disqus