congr / world

2 stars 1 forks source link

LeetCode : 733. Flood Fill #441

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/flood-fill/

image

congr commented 5 years ago

O(R*C) => O(N) : Every cell on the grid is visited once.

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        dfs(image, sr, sc, image[sr][sc], newColor);

        return image;
    }

    int[] dy = {0,-1,0,1};
    int[] dx = {-1,0,1,0};
    void dfs(int[][] image, int y, int x, int oldColor, int newColor) {
        image[y][x] = newColor;

        for (int d = 0; d<4; d++) {
            int ny = y + dy[d];
            int nx = x + dx[d];

            if (ny >= 0 && nx >= 0 && ny < image.length && nx < image[0].length) {
                if (image[ny][nx] == oldColor && image[ny][nx] != newColor)
                    dfs(image, ny, nx, oldColor, newColor);
            }
        }
    }
}